个人笔记--Android 和 服务器通信 的乱码问题

来源:互联网 发布:chrome ie tab mac 编辑:程序博客网 时间:2024/05/22 11:50

最近在做Android项目,客户端的URL中有中文,传到服务器后全是乱码。

Web服务器:tomcat

框架:struts2

数据库:oracle

Tomcat中字符集的配置:

    <Connector         URIEncoding="utf-8"         connectionTimeout="20000"         port="8099"         protocol="HTTP/1.1"         redirectPort="8443"         useBodyEncodingForURI="true"/>

项目里面也有过滤器,但是手机传过去的代码就是乱码,网上的好多人的方法根本就不起效。

这个代码适用于 HttpClient 中的 HttpGet、HttpPost和URLConnection,主要的就是   Content-Type  charset  :

protected JSONObject doInBackground(String... params) {HttpClient client = new DefaultHttpClient();HttpParams parm = client.getParams();parm.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);parm.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);HttpGet httpGet=new HttpGet(params[0]);//**解决乱码的代码   其它方法都不顶用**//httpGet.addHeader("Content-Type", "content=text/html; charset=UTF-8");httpGet.addHeader("charset", HTTP.UTF_8);   //**解决乱码的代码   其它方法都不顶用**//try {HttpResponse response =client.execute(httpGet);// 获取响应码int code = response.getStatusLine().getStatusCode();if (code == 200) {// 获取响应内容InputStream is =response.getEntity().getContent();BufferedInputStream bis = new BufferedInputStream(is);byte[] buf = new byte[1024];StringBuffer strBuf = new StringBuffer("");int len = -1;while ((len = bis.read(buf)) != -1) {strBuf.append(new String(buf, 0, len));}JSONObject obj = new JSONObject(strBuf.toString());return obj;}elsereturn null;} catch (Exception e) {e.printStackTrace();return null;}}


0 0
原创粉丝点击