HTTP客户端代码片段

 

 

 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         }

 

posted @ 2016-06-17 09:14  月色深潭  阅读(379)  评论(0编辑  收藏  举报