使用Apache HttpClient遇到的一些问题
关于客户端用post对象提交,服务端获取post对象中参数。
利用request.getParameter()获取不到参数值,与Content-Type有关系。
如果request.getParameter()获取不到参数值,可以利用request.getInputStream()或request.getReader()来获取。
客户端:
HttpClient httpClient = new DefaultHttpClient();
post = new HttpPost(url);
// 构造消息头
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Connection", "Close");
// 构建消息实体
StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 发送Json格式的数据请求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
服务端:
InputStream inputStream = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
StringBuffer stringBuffer = new StringBuffer();
String str= "";
while((str = br.readLine()) != null){
stringBuffer.append(str);
}
JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
还没有评论,来说两句吧...