使用Apache HttpClient遇到的一些问题

男娘i 2022-05-26 12:36 376阅读 0赞

关于客户端用post对象提交,服务端获取post对象中参数。
利用request.getParameter()获取不到参数值,与Content-Type有关系。
如果request.getParameter()获取不到参数值,可以利用request.getInputStream()或request.getReader()来获取。

  1. 客户端:
  2. HttpClient httpClient = new DefaultHttpClient();
  3. post = new HttpPost(url);
  4. // 构造消息头
  5. post.setHeader("Content-type", "application/json; charset=utf-8");
  6. post.setHeader("Connection", "Close");
  7. // 构建消息实体
  8. StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
  9. entity.setContentEncoding("UTF-8");
  10. // 发送Json格式的数据请求
  11. entity.setContentType("application/json");
  12. post.setEntity(entity);
  13. HttpResponse response = httpClient.execute(post);
  14. 服务端:
  15. InputStream inputStream = request.getInputStream();
  16. BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
  17. StringBuffer stringBuffer = new StringBuffer();
  18. String str= "";
  19. while((str = br.readLine()) != null){
  20. stringBuffer.append(str);
  21. }
  22. JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());

发表评论

表情:
评论列表 (有 0 条评论,376人围观)

还没有评论,来说两句吧...

相关阅读