//访问Url,发送数据,获得返回数据。
public String readParse(String data) {
String str="";
//synUrl为你要访问的URL
HttpPost httpRequest = new HttpPost(synUrl);
try {
HttpClient client = new DefaultHttpClient();
// 请求超时
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
// 读取超时
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
//对数据进行编码
data=URLEncoder.encode(data,"UTF-8");
//将数据放入到string entity当中,发送的主题内容
StringEntity strEntity=new StringEntity(data);
strEntity.setContentEncoding("UTF-8");
//将发送的数据放入到http请求当中
httpRequest.setEntity(strEntity);
//设置请求头部
httpRequest.setHeader("Content_Type","application/json;charset=UTF-8");
//发送请求,接收响应数据
HttpResponse httpResponse =client.execute(httpRequest);
httpResponse.setHeader("content_type","application/json;charset=UTF-8");
// 如果状态码为200,接收正常
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 取出回应字串
str=EntityUtils.toString(httpResponse.getEntity()).trim();
strResult = str;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return strResult;
}
最近使用学习开发android,涉及到前后台通信编码问题,上面给出android端代码。
网上还有另一种方式:
public boolean post(String username, String password) throws Exception {
username = URLEncoder.encode(username);// 中文数据需要经过URL编码
password = URLEncoder.encode(password);
String params = "username=" + username + "&password=" + password;
byte[] data = params.getBytes();
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(3000);
//这是请求方式为POST
conn.setRequestMethod("POST");
//设置post请求必要的请求头
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 请求头, 必须设置
conn.setRequestProperty("Content-Length", data.length + "");// 注意是字节长度, 不是字符长度
conn.setDoOutput(true);// 准备写出
conn.getOutputStream().write(data);// 写出数据
return conn.getResponseCode() == 200;
}
虽然使用了不同的两种文本传输格式,但是都用到了URLEncoder类,这个类是用来进行编码的,因为汉字在传输过程中会出现字节丢失,因此需要重新编码,来解决这个问题。
下面是编码的实验:
public class test {
public static void main(String args[])
{
try {
String str="你";
//编码一次
String res=URLEncoder.encode(str,"UTF-8");
System.out.println("encode one:"+res);
//编码第两次
res=URLEncoder.encode(res,"UTF-8");
System.out.println("encode two:"+res);
//解码一次
res=URLDecoder.decode(res,"UTF-8");
System.out.println("dencode one:"+res);
//解码两次
res=URLDecoder.decode(res,"UTF-8");
System.out.println("dencode two:"+res);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* encode one:%E4%BD%A0
* encode two:%25E4%25BD%25A0
* dencode one:%E4%BD%A0
* dencode two:你
*/
}
实验可以发现,encode two:只是在原来的基础上增加了%25,经过编码的传输,到服务器端在通过URLDecoder类就可以解码,这样就不会出现乱码问题。
没有编码情况下,发送“你”字的捕包如下:
POST /Todo/admin/syn.action HTTP/1.1
content_type: application/json;charset=UTF-8
Content-Length: 320
Content-Type: application/json;charset=UTF-8
Content-Encoding: UTF-8
Host: 10.16.15.88:9091
Connection: Keep-Alive
User-Agent: Apache-HttpClient/UNAVAILABLE (java 1.4)
{"title":"?"}