java代码调用http接口

 1 public static void main(String[] args) throws Exception {
 2         //请求的webservice的url
 3         URL url = new URL("http://");
 4         //创建http链接
 5         HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 6     
 7         //设置请求的方法类型
 8         httpURLConnection.setRequestMethod("POST");
 9         
10         //设置请求的内容类型
11         httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
12         
13         //设置发送数据
14         httpURLConnection.setDoOutput(true);
15         //设置接受数据
16         httpURLConnection.setDoInput(true);
17         
18         //发送数据,使用输出流
19         OutputStream outputStream = httpURLConnection.getOutputStream();
20         //发送的soap协议的数据
21         String requestXmlString = requestXml("北京");
22     
23         String content = "user_id="+ URLEncoder.encode("123", "gbk");
24         
25         //发送数据
26         outputStream.write(content.getBytes());
27     
28         //接收数据
29         InputStream inputStream = httpURLConnection.getInputStream();
30     
31         //定义字节数组
32         byte[] b = new byte[1024];
33         
34         //定义一个输出流存储接收到的数据
35         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
36         
37         //开始接收数据
38         int len = 0;
39         while (true) {
40             len = inputStream.read(b);
41             if (len == -1) {
42                 //数据读完
43                 break;
44             }
45             byteArrayOutputStream.write(b, 0, len);
46         }
47         
48         //从输出流中获取读取到数据(服务端返回的)
49         String response = byteArrayOutputStream.toString();
50         
51         System.out.println(response);
52         
53     }

 

转载于:https://www.cnblogs.com/jason123/p/6736251.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值