码迷,mamicode.com
首页 > Web开发 > 详细

HTTP客户端代码片段

时间:2016-06-17 09:47:45      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

 

 

 1 代码片段:
 2 
 3 public HttpURLConnection connection = null;
 4 
 5 设置connection属性
 6 URL url = new URL(urlPath);
 7 connection = (HttpURLConnection) url.openConnection();
 8 connection.setDoOutput(true);
 9 connection.setDoInput(true);
10 connection.setRequestMethod("POST");
11 connection.setUseCaches(false);
12 connection.setInstanceFollowRedirects(true);
13 connection.setRequestProperty("Content-type", "application/json");
14 connection.setRequestProperty("Content-encoding", "GBK");
15 //connection.setRequestProperty("Content-encoding", "UTF-8");
16 connection.setRequestProperty("Accept", "application/json");
17 connection.connect();
18 
19 
20 
21 发送请求
22 output = connection.getOutputStream();
23 output.write(request.getBytes());
24 output.flush();
25 
26 接受响应
27 reader = new BufferedReader(new InputStreamReader(
28                 connection.getInputStream()));
29 String st;
30 StringBuffer stb = new StringBuffer();
31 while (null != (st = reader.readLine())) {
32 stb.append(st);
33 }
34 
35 
36 关闭connection
37 if (null != connection) {
38             connection.disconnect();
39         }

 

HTTP客户端代码片段

标签:

原文地址:http://www.cnblogs.com/moonpool/p/5592923.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!