ResponseEntity发送乱码,HttpResponse response接收乱码问题解决

在通过HttpClient或URL方式请求数据的过程中,难免会出现乱码的问题,笔者在项目开发过程中就遇到了此问题,在网上找了一堆资料,都是在接收端解决问题,忽略了发送端的编码问题,所以在接收端所有办法都用了还是不行,现在把解决的办法贴出业,希望能帮助到遇见相同问题的朋友。直接上代码

一、接收端

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public static  JSONObject post(String url)
    {
        HttpClient httpClient = new DefaultHttpClient();  
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");  
        
        
        try {
              
            HttpResponse httpResponse = httpClient.execute(httpPost);  
            InputStream inStream =     httpResponse.getEntity().getContent();  
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"utf-8"));  //请注意这里的编码 
            StringBuilder strber = new StringBuilder();    
            String line = null;    
            while ((line = reader.readLine()) != null)     
                strber.append(line );    
            inStream.close();    
            JSONObject jsonObj = new JSONObject(strber.toString());
            return jsonObj;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            //return null;
        }
        return null;
    }

二、发送端

这里用的是springMVC

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/userInfo")
    public HttpEntity userInfo(HttpServletRequest request){

            String js = "这是放的是要发送的html文本";
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = new MediaType("text","html",Charset.forName("utf-8"));
            headers.setContentType(mediaType);

            return new ResponseEntity(js,headers, HttpStatus.OK);

}

你可能感兴趣的:(ResponseEntity发送乱码,HttpResponse response接收乱码问题解决)