Java 使用HttpClient进行模拟请求

一、 环境

jdk版本: jdk1.8+

HttpClient版本: httpClient4.5+

二、 下载jar包

1、 下载HttpClient的jar包,在apache官网

       下载地址: http://hc.apache.org/downloads.cgi

三、 使用步骤(转)

  1.  创建HttpClient对象,HttpClients.createDefault()。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象,HttpPost httpPost = new HttpPost(url)。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。List<NameValuePair> valuePairs = new LinkedList<NameValuePair>();valuePairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));httpPost.setEntity(formEntity)。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接

      HttpClient在4.3版本以后声明HttpClient的方法和以前略有区别,不再是直接声明new DefaultHttpClient() .

四、 代码示例

     /**
	 * 
	    * @Title: httpGet
	    * @Description: TODO(http  get请求)
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	public static String httpGet(){
		//httpClient
	    HttpClient httpClient = HttpClients.createDefault();

	    // get method
	    HttpGet httpGet = new HttpGet("https://www.baidu.com");
	  
	    //response
	    HttpResponse response = null;  
	    try{
	        response = httpClient.execute(httpGet);
	    }catch (Exception e) {} 

	    //get response into String
	    String result="";
	    try{
	        HttpEntity entity = response.getEntity();
	        result=EntityUtils.toString(entity,"UTF-8");
	    }catch (Exception e) {} 
	    finally {
		}
	    
	    return result;
	}
	
	/**
	 * 
	    * @Title: httpPost
	    * @Description: TODO(http post请求)
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	public static String httpPost(){
		//httpClient
	    HttpClient httpClient = HttpClients.createDefault();

	    // get method
	    HttpPost httpPost = new HttpPost("https://www.baidu.com");    
	  
	    // set header
	    httpPost.setHeader("Content-Type","application/x-www-form-urlencoded"); 

	    //set params post参数
	    List<NameValuePair> params = new ArrayList<NameValuePair>();
	    
	    //添加post参数
	    params.add(new BasicNameValuePair("param", "value"));
	    
	    try{
	        httpPost.setEntity(new UrlEncodedFormEntity(params));
	    }catch (Exception e) {} 

	    //response
	    HttpResponse response = null;  
	    try{
	        response = httpClient.execute(httpPost);
	    }catch (Exception e) {}
	    
	    //get response into String
	    String result="";
	    try{
	        HttpEntity entity = response.getEntity();
	        result=EntityUtils.toString(entity,"UTF-8");
	    }catch (Exception e) {}
	    finally {
			
		}
	    
	    return result;    
	}

猜你喜欢

转载自blog.csdn.net/wawawawawawaa/article/details/81429081
今日推荐