HTTP客户端代码片段
Posted 月色深潭
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }
以上是关于HTTP客户端代码片段的主要内容,如果未能解决你的问题,请参考以下文章