HttpPost (URLConnection)传参数中文乱码

 1 client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000000);

 2         client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 1000000);

 3         HttpPost post = new HttpPost(url);

 4         NameValuePair rq = new BasicNameValuePair("rq", requestObj.toString());

 5         BasicNameValuePair data_type = new BasicNameValuePair("type", req_type);

 6         NameValuePair sid = new BasicNameValuePair("sid", "web123");

 7         List<NameValuePair> list = new ArrayList<NameValuePair>();

 8         list.add(rq);

 9         list.add(sid);

10         list.add(data_type);

11         StringEntity entity = new UrlEncodedFormEntity(list, HTTP.UTF_8); 12         post.setEntity(entity);

13         HttpResponse res = client.execute(post);

14         String respStr = EntityUtils.toString(res.getEntity(),HTTP.UTF_8); 15         this.inputStream = new ByteArrayInputStream(respStr.toString().getBytes("utf-8"));

16         return SUCCESS;

方式二:

 1 //1、URL对象创建一个应用程序与url之间链接urlconnection对象 

 2         URL connectUrl = new URL(url);

 3         HttpURLConnection conn = (HttpURLConnection) connectUrl.openConnection();

 4         //2、设置属性

 5         //post请求必须设置的两个

 6         conn.setDoInput(true);

 7         conn.setDoOutput(true);

 8         //设置属性

 9         conn.setUseCaches(false);

10         conn.setRequestProperty("accept", "*/*");

11         conn.setRequestProperty("connection", "Keep-Alive");

12         //打开与url之间的连接

13         conn.connect();

14         //如果使用URLconnection既要读取输入流 又要传参数 那么一定要先使用输出流 在使用输入流

15         //getOutputStream 中包含了connect 也就是说使用了getoutputStream的时候connect可以不写

16         OutputStream os = conn.getOutputStream();

17         //设置编码 防止到服务端出现中文乱码

18         OutputStreamWriter ow = new OutputStreamWriter(os, HTTP.UTF_8);

19         PrintWriter pw = new PrintWriter(ow,true);

20         //之前所有的参数只是写入写出流的缓存中并没有发送到服务端,执行下面这句话后表示将参数信息发送到服务端

21         pw.println("rq="+requestObj.toString()+"&sid=web123&type="+req_type);

22         pw.flush();

23         //获取服务端返回的信息

24         InputStream is = conn.getInputStream();

25         //设置编码 防止读取到的数据乱码

26         BufferedReader br = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8));

27         

28         String line = null;

29         String respStr = "";

30         while((line=br.readLine())!=null){

31             respStr+=line;

32         }

33         this.inputStream = new ByteArrayInputStream(respStr.toString().getBytes("utf-8"));

34         return SUCCESS;

在服务端接收到requestObj.toString()中文乱码 可用在创建Entity时指定编码  StringEntity entity = new UrlEncodedFormEntity(list, HTTP.UTF_8);

在返回的数据中也出现了中文乱码 可使用EntityUtils.toString指定字符编码     String respStr = EntityUtils.toString(res.getEntity(),HTTP.UTF_8);

你可能感兴趣的:(urlconnection)