json入参的接口乱码问题解决

本文介绍了一种通过使用原生UrlConnection解决接口请求中JSON参数导致乱码问题的方法,包括关键代码实现及封装过程。重点强调了设置头部信息以确保UTF-8编码正确传输。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

需求背景:由于一些接口并没有采用常规的form形式,而是用一个json作为入参,形如{"userName":"zhangsan","password":"123456"}.

这种情况下用restTemplate也行,用httpClient也行,但是restTempalte和httpClient都可能有乱码问题。我这里用最原生的UrlConnection来解决,加上一些头部信息,即可解决乱码,很爽。

 

关键代码:

 

public static void post(String url, String param ) throws Exception{
        String charset = "UTF-8"; 
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);  Triggers POST.
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);

        try (OutputStream output = connection.getOutputStream()) {
          output.write(param.getBytes(charset));
        }

        InputStream response = connection.getInputStream();
        String result= InputStreamTOString(response, "UTF-8");
        System.out.println("result^_^"+result);
      }

 

 

final static int BUFFER_SIZE = 4096;  
       
     /  

  • 将InputStream转换成某种字符编码的String  
  • @param in  
  • @param encoding  
  • @return  
  • @throws Exception  
             */  
                 public static String InputStreamTOString(InputStream in,String encoding) throws Exception{  
                 
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
                byte[] data = new byte[BUFFER_SIZE];  
                int count = -1;  
                while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
                    outStream.write(data, 0, count);  
                 
                data = null;  
                return new String(outStream.toByteArray(),encoding);  
            }  
 
 

具体代码我已经封装在V3架构里面的HttpClientUtil的postWithJson方法中,为了保持统一,本方法强制用UTF-8编码。

只要接受3个参数,具体看源码即可。

 

refurl:http://stackoverflow.com/questions/7181534/http-post-using-json-in-java

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值