使用httpclient发送get、post请求
2016-06-21 17:24
591 查看
使用httpclient发送get、post请求是最常用的两种web请求
示例代码如下
示例代码如下
1.get请求 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("http://targethost/homepage"); CloseableHttpResponse response1 = httpclient.execute(httpGet); // 建立的http连接,仍旧被response1保持着,允许我们从网络socket中获取返回的数据 // 为了释放资源,我们必须手动消耗掉response1或者取消连接 //(使用CloseableHttpResponse类的close方法) try { //response1.getStatusLine(); //此处可以通过responses获取响应内容,getEntity方法获取响应体。 HttpEntity entity1 = response1.getEntity(); // do something useful with the response body // and ensure it is fully consumed EntityUtils.consume(entity1); } finally { response1.close(); } 2.post 请求 Post请求关键在于发送参数,参数分为两种:一种是键值对,另一种是纯文本。 HttpClient 均支持这两种方式: HttpPost httpPost = new HttpPost("url"); // 拼接键值参数 // List nvps = new ArrayList (); // nvps.add(new BasicNameValuePair("username", "vip")); // nvps.add(new BasicNameValuePair("password", "secret")); // httpPost.setEntity(new UrlEncodedFormEntity(nvps)); //使用文本参赛 HttpEntity he = new StringEntity("{\"method\":\"\",\"params\":[]}"); httpPost.setEntity(he); httpPost.addHeader("Cookie","AwAAY&dp0gkAIIugIgJOWqoYA"); httpPost.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0"); httpPost.addHeader("Host", "www.yahoo.com"); CloseableHttpResponse response2 = httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2 = response2.getEntity(); InputStream is = entity2.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String content = null; while ((content = br.readLine()) != null) { int count = StringUtils.countMatches(content, "conversation"); System.out.println(count); } br.close(); // 消耗掉response EntityUtils.consume(entity2); } finally { response2.close(); }
相关文章推荐
- 使用httpclient下载远程文件
- httpClient超时设置
- TCP协议中的三次握手四次挥手问题
- The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
- 计算机网络——OSI、TCP/IP协议族详解
- 高性能网络编程
- 网络编程
- 浏览器的工作原理:新式网络浏览器幕后揭秘
- SIP与http的联系
- [Java学习] java实现http的Post、Get、代理访问请求
- Android网络请求
- 五层原理体系结构的简单分析
- 使用异步httpclient框架做get,post提交数据
- TCP/IP、Http、Socket的区别
- ASYNC_NETWORK_IO 或 NETWORK_IO
- HttpURLConnection与HttpClient区别及联系
- openstack 网络
- 启用新博客 http://taney.coding.me , 欢迎访问!
- TCP-IP 三次握手-四次挥手
- http://blog.csdn.net/mr_raptor/article/category/799879/3