java WebService接口调用,传JSON参数

  1. import java.io.IOException;
  2. import java.io.InputStream;
  3. import java.io.OutputStreamWriter;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. public class Copy_2_of_PostDemo {
  7. final static String url = "";
  8. final static String params = "{"id":"12345"}";
  9. /**
  10. * 发送HttpPost请求
  11. *
  12. * @param strURL
  13. * 服务地址
  14. * @param params
  15. * json字符串,例如: "{ "id":"12345" }" ;其中属性名必须带双引号<br/>
  16. * @return 成功:返回json字符串<br/>
  17. */
  18. public static String post(String strURL, String params) {
  19. System.out.println(strURL);
  20. System.out.println(params);
  21. try {
  22. URL url = new URL(strURL);// 创建连接
  23. HttpURLConnection connection = (HttpURLConnection) url
  24. .openConnection();
  25. connection.setDoOutput(true);
  26. connection.setDoInput(true);
  27. connection.setUseCaches(false);
  28. connection.setInstanceFollowRedirects(true);
  29. connection.setRequestMethod("POST"); // 设置请求方式
  30. connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
  31. connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
  32. connection.connect();
  33. OutputStreamWriter out = new OutputStreamWriter(
  34. connection.getOutputStream(), "UTF-8"); // utf-8编码
  35. out.append(params);
  36. out.flush();
  37. out.close();
  38. // 读取响应
  39. int length = (int) connection.getContentLength();// 获取长度
  40. InputStream is = connection.getInputStream();
  41. if (length != -1) {
  42. byte[] data = new byte[length];
  43. byte[] temp = new byte[512];
  44. int readLen = 0;
  45. int destPos = 0;
  46. while ((readLen = is.read(temp)) > 0) {
  47. System.arraycopy(temp, 0, data, destPos, readLen);
  48. destPos += readLen;
  49. }
  50. String result = new String(data, "UTF-8"); // utf-8编码
  51. System.out.println(result);
  52. return result;
  53. }
  54. } catch (IOException e) {
  55. // TODO Auto-generated catch block
  56. e.printStackTrace();
  57. }
  58. return "error"; // 自定义错误信息
  59. }
  60. public static void main(String[] args) {
  61. post(url, params);
  62. }
  63. }
经验分享 程序员 微信小程序 职场和发展