Java | HTTP请求,form-data方式及处理中文乱码问题

起因

平时调用HTTP请求,一般传递的都是JSON,或者字符串参数。这次遇到了需要以form-data表单的方式提交数据。其中还遇到了推过去的数据中文乱码问题,也一并记录。

代码示例

httpclient的方式建立连接,引入的jar包主要有:

  • httpclient-4.3.3.jar
  • httpcore-4.3.2.jar
  • httpmime-4.3.3.jar
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public static String httpPost(String url,String data){
    
    
		CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(Charset.forName("utf-8"));//设置请求的编码格式
        ContentType contentType = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));//重新设置UTF-8编码,默认编码是ISO-8859-1
//        builder.addTextBody("jmsg", data, ContentType.MULTIPART_FORM_DATA); 
        builder.addTextBody("jmsg", data, contentType); 


        HttpEntity multipart = builder.build();
        httpPost.setEntity(multipart);
        CloseableHttpResponse response = null;
		try {
    
    
			response = httpClient.execute(httpPost);
		} catch (ClientProtocolException e) {
    
    
			logger.error("httpClient response 初始化异常" + e);
		} catch (IOException e) {
    
    
			logger.error("httpClient response IO异常" + e);
		}
        HttpEntity responseEntity = response.getEntity();
        String sResponse = null;
		try {
    
    
			sResponse = EntityUtils.toString(responseEntity, "UTF-8");
		} catch (ParseException e) {
    
    
			logger.error("httpClient 转换异常" + e);
		} catch (IOException e) {
    
    
			logger.error("httpClient sResponse IO异常" + e);
		}
        logger.info("httpPost 返回结果"+sResponse);
		return sResponse;
	}

中文乱码引起原因及解决方案

...
builder.addTextBody("jmsg", data, ContentType.MULTIPART_FORM_DATA);
...

中文乱码原因是如果使用原ContentType.MULTIPART_FORM_DATA ,点进去查看源码可以发现,其编码是 ISO-8859-1,而一般接收方编码都是UTF-8。因此将上面的代码改成如下,不使用默认的ContentType.MULTIPART_FORM_DATA,而是新建一个UTF-8编码的对象,即可解决中文乱码问题。


...
ContentType contentType = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));//重新设置UTF-8编码,默认编码是ISO-8859-1
builder.addTextBody("jmsg", data, contentType); 
...

猜你喜欢

转载自blog.csdn.net/u012294515/article/details/118674398