首页 > Web开发 > 详细

使用HttpClient4发送 http请求

时间:2016-01-04 18:24:16      阅读:289      评论:0      收藏:0      [点我收藏+]
   最近在使用httpclient,我也是初学,把一些用法和心得和大家分享下,共同学习,如果使用httpclient 需要依赖httpclient_*.jar 官方下载地址
    下载下来将lib下的jar导入工程。
   以下代码使用httpclient-4.5.1。
  1.使用httpclient 发送Get和Post请求
   Get 请求
    CloseableHttpClient httpclient = HttpClients.createDefault();
      //get 请求
	  CloseableHttpClient httpclient = HttpClients.createDefault();
	     try {
	    HttpGet httpGet = new HttpGet("http://www.baidu.com");
	   System.out.println("Executing get request " + httpGet.getURI());
	   CloseableHttpResponse response = httpclient.execute(httpGet);
	       try {
	          System.out.println(response.getStatusLine()); //返回请求的响应码
	            httpGet.abort();
	         } finally {
	             response.close();
	         }
	       } finally {
	            httpclient.close();
	      }
	//Post 请求            
     CloseableHttpClient httpclient = HttpClients.createDefault();
	   try {
	       HttpPost httpPost = new HttpPost("http://www.baidu.com");
	   List<NameValuePair> pairList = new ArrayList<NameValuePair>();
	    pairList.add(new BasicNameValuePair("参数名","参数值"));
	   System.out.println("Executing get request " + httpPost.getURI());
	   CloseableHttpResponse response = httpclient.execute(httpPost);
	    try {
	       System.out.println(response.getStatusLine()); //返回请求的响应码
	          httpPost.abort();
	       } finally {
	          response.close();
	        }
	    } finally {
	            httpclient.close();
	  }
	
   	
	


本文出自 “7854772” 博客,请务必保留此出处http://7864772.blog.51cto.com/7854772/1731407

使用HttpClient4发送 http请求

原文:http://7864772.blog.51cto.com/7854772/1731407

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!