[关闭]
@ruoli 2016-10-26T08:01:25.000000Z 字数 1378 阅读 2219

Java模拟发送Post请求

Java基础


此工具类,默认使用UTF-8编码,发送和接受都已通过验证,没有乱码问题

  1. public class HttpRequestTool {
  2. /**
  3. * 向指定 URL 发送POST方法的请求
  4. *
  5. * @param url
  6. * 发送请求的 URL
  7. * @param param
  8. * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  9. * @return 所代表远程资源的响应结果
  10. */
  11. public static String sendPost(String urlStr, String param) throws Exception{
  12. URL url = new URL(urlStr);
  13. URLConnection connection = url.openConnection();
  14. /**
  15. * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。
  16. * 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
  17. */
  18. connection.setDoOutput(true);
  19. /**
  20. * 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
  21. */
  22. OutputStreamWriter out = new OutputStreamWriter(connection
  23. .getOutputStream(), "UTF-8");
  24. out.write(param); //post的关键所在!
  25. // remember to clean up
  26. out.flush();
  27. out.close();
  28. /**
  29. * 这样就可以发送一个看起来象这样的POST:
  30. * POST /jobsearch/jobsearch.cgi HTTP 1.0 ACCEPT:
  31. * text/plain Content-type: application/x-www-form-urlencoded
  32. * Content-length: 99 username=bob password=someword
  33. */
  34. // 一旦发送成功,用以下方法就可以得到服务器的回应:
  35. String sCurrentLine;
  36. String sTotalString;
  37. sCurrentLine = "";
  38. sTotalString = "";
  39. InputStream l_urlStream = connection.getInputStream();
  40. BufferedReader l_reader = new BufferedReader(new InputStreamReader(
  41. l_urlStream,"UTF-8"));
  42. while ((sCurrentLine = l_reader.readLine()) != null) {
  43. sTotalString += sCurrentLine;
  44. }
  45. l_urlStream.close();
  46. l_reader.close();
  47. return sTotalString;
  48. }
  49. public static void main(String[] args) throws Exception {
  50. String paramString="header=ADD&compressed=输变电检修单";
  51. sendPost("http://localhost/PcServer/serviceRequest",paramString);
  52. }
  53. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注