Post请求url接口传json数据

 1 /**
 2      * 向指定 URL 发送POST方法的请求
 3      * 
 4      * @param url
 5      *            发送请求的 URL
 6      * @param param
 7      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 8      * @return 所代表远程资源的响应结果
 9      */
10     public static String sendPostByJson(String url, String jsString) {
11         String result = "";
12         try {
13             // 创建url资源
14             URL RelUrl = new URL(url);
15             // 建立http连接
16             HttpURLConnection conn = (HttpURLConnection) RelUrl.openConnection();
17             // 设置允许输出
18             conn.setDoOutput(true);
19 
20             conn.setDoInput(true);
21 
22             // 设置不用缓存
23             conn.setUseCaches(false);
24             // 设置传递方式
25             conn.setRequestMethod("POST");
26             // 设置维持长连接
27             conn.setRequestProperty("Connection", "Keep-Alive");
28             // 设置文件字符集:
29             conn.setRequestProperty("Charset", "UTF-8");
30             //转换为字节数组
31             byte[] data = (jsString).getBytes();
32             // 设置文件长度
33             conn.setRequestProperty("Content-Length", String.valueOf(data.length));
34 
35             // 设置文件类型:
36             conn.setRequestProperty("contentType", "application/json");
37 
38 
39             // 开始连接请求
40             conn.connect();
41             OutputStream  out = conn.getOutputStream();     
42             // 写入请求的字符串
43             out.write((jsString).getBytes());
44             out.flush();
45             out.close();
46 
47             System.out.println(conn.getResponseCode());
48 
49             // 请求返回的状态
50             if (conn.getResponseCode() == 200) {
51                 System.out.println("连接成功");
52                 // 请求返回的数据
53                 InputStream in = conn.getInputStream();
54                 try {
55                     byte[] data1 = new byte[in.available()];
56                     in.read(data1);
57                     // 转成字符串
58                     result = new String(data1);
59                     System.out.println(result);
60                 } catch (Exception e1) {
61                     // TODO Auto-generated catch block
62                     e1.printStackTrace();
63                 }
64             } else {
65                 System.out.println("no++");
66             }
67 
68         } catch (Exception e) {
69 
70         }
71         return result;
72 }

 

转载于:https://www.cnblogs.com/moonlignt/p/7299555.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值