用HttpURLConnection来完成HTTP发送报文接收报文!

 1 public  String sendMsg(String url, byte[] PostData) {
 2         String content = null;
 3         URL urls = null;
 4         try {
 5         urls = new URL(url);
 6         HttpURLConnection httpURLConnection = (HttpURLConnection) urls .openConnection();
 7          // 设置连接时间
 8         httpURLConnection.setConnectTimeout(3000);
 9         // 打开输入流,以便从服务器获取数据
10         httpURLConnection.setDoInput(true);
11         // 打开输出流,以便向服务器提交数据
12         httpURLConnection.setDoOutput(true);
13          // 设置以POST方式提交数据
14         httpURLConnection.setRequestMethod("POST");
15         // 使用POST不能使用缓存
16         httpURLConnection.setUseCaches(false);
17         // 设置请求的类型是文本类型
18         httpURLConnection.setRequestProperty("Content-Type",
19         "application/x-www-form-urlencoded");
20         // 设置请求体的长度
21         httpURLConnection.setRequestProperty("Content-Length",
22         String.valueOf(PostData.length));
23         // 获得输出流,向指定的Url写入数据
24         OutputStream outputStream = httpURLConnection.getOutputStream();
25         outputStream.write(PostData);
26         int response = httpURLConnection.getResponseCode(); 
27                 // 获得服务器响应码
28         if (response == HttpURLConnection.HTTP_OK) {
29         InputStream inputStream= httpURLConnection.getInputStream();
30         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "gbk"));
31                         StringBuilder builder = new StringBuilder();
32                         String line = null;
33                         while ((line = reader.readLine()) != null) {
34                             builder.append(line).append("\n");
35                         }
36                         content = builder.toString();
37                     }
38         }catch (IOException e) {
39         e.printStackTrace();
40         }
41         return content;
42         }            

 

转载于:https://www.cnblogs.com/oldzhang1222/p/8250805.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值