HttpClient使用总结

HttpClient使用总结

一、HttpClient使用步骤

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

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

二、请求参数接收

httpClient可以发送不同类型的请求参数,当然对应的接口接收参数的方式也需相应的调整

  1. httpClient请求
    情况一:当参数类型为非json类型(get请求、非json参数类型post请求),则后台接收参数可以直接使用@RequestParam

    @RequestMapping(value="/login")
    public String login(HttpServletRequest request,HttpServletResponse response,
       	@RequestParam(value="username") String username,
       	@RequestParam(value="password") String password){
       	System.out.println("username: " + username);
       	System.out.println("password: " + password);
    }
    
    

    情况二:当参数类型为json类型,则需先通过StringEntity设置ContentType=‘application/json’,后台接收需要使用@RequesBody
    方式1:Map集合接收

    @RequestMapping(value="/login")
    public String login(HttpServletRequest request,HttpServletResponse response,
      	@RequesBody Map<String,Object> map){
      	System.out.println("username: " + map.get("username"));
      	System.out.println("password: " + map.get("password"));
    }
    

    方式2:POJO对象接收

    @RequestMapping(value="/login")
    public String login(HttpServletRequest request,HttpServletResponse response,
      	@RequesBody User user){
      	System.out.println("username: " + user.getUsername());
      	System.out.println("password: " + user.getPassword());
    }
    
  2. ajax请求(非HttpClient请求)
    情况一:后台可以直接使用@RequestParam 或者request.getParameter获取参数。

    //参数
    var json = {
    	"username" : $("#username").val(),
    	"password" : $("#password").val()
    };
    //发送请求
    $.ajax({
    	url : "http://localhost:9080/es-ext/webservice/login",
    	type : "POST",
    	async : true,
    	data : json,
    	dataType : 'json',
    	success : function(data) {
    	if (data.msg === "success") {
    			$("#errorMsg").remove();
    		} else {
    			if ($("#errorMsg").length <= 0) {
    				$("form[name=loginForm]").append(errorMsg);
    			}
    		}
    	}
    });
    

    情况二:后台需要使用@RquestBody获取参数。

    //参数
    var json = {
         "username" : $("#username").val(),
         "password" : $("#password").val()
    };
    //发送请求
    $.ajax({
    	url : "http://localhost:9080/es-ext/webservice/login",
    	type : "POST",
    	async : true,
    	contentType : "application/json",
    	data : JSON.stringify(json),
    	dataType : 'json',
    	success : function(data) {
    		if (data.userstatus === "success") {
    			$("#errorMsg").remove();
    		} else {
    			if ($("#errorMsg").length <= 0) {
    				$("form[name=loginForm]").append(errorMsg);
    			}
    		}
    	}
    });
    

三、响应结果解析

  1. 响应结果为json类型:通过JSONObject进行解析

    public static void main(String[] args) {
    
    	// 测试接口地址
    	String url = "http://localhost:9080/es-ext/webservice/login";
    
    	// 测试参数
    	List<BasicNameValuePair> urlParameters = new ArrayList<>();
    	urlParameters.add(new BasicNameValuePair("username", "zhangsan"));
    	urlParameters.add(new BasicNameValuePair("password", "123456"));
    
    	// 发送请求(HttpClient, Closeable的实现类,可实现自动close)
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	CloseableHttpResponse response = null;
    	HttpPost post = new HttpPost(url);
    	try {
    		post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));// 设置post请求的参数
    		post.setConfig(requestConfig); // 设置请求参数
    		response = httpclient.execute(post);
    		// 判断网络连接状态码是否正常(0--200都数正常)
    		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
    			// 返回值为json,使用JSONObject解析json
    			JSONObject jsonObject = JSONObject.fromObject(content);
    			System.out.println(jsonObject.getString("code") + ":" + jsonObject.getString("msg"));
    		}
    		EntityUtils.consume(response.getEntity());// 完全消耗
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (null != response)
    				response.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    
  2. 响应结果为xml类型:通过DocumentHelper进行解析

    public static void main(String[] args) {
    
    	// 测试接口地址
    	String url = "http://localhost:9080/es-ext/webservice/login";
    
    	// 测试参数
    	List<BasicNameValuePair> urlParameters = new ArrayList<>();
    	urlParameters.add(new BasicNameValuePair("username", "zhangsan"));
    	urlParameters.add(new BasicNameValuePair("password", "123456"));
    
    	// 发送请求(HttpClient, Closeable的实现类,可实现自动close)
    	CloseableHttpClient httpclient = HttpClients.createDefault();
    	CloseableHttpResponse response = null;
    	HttpPost post = new HttpPost(url);
    	try {
    		post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));// 设置post请求的参数
    		post.setConfig(requestConfig); // 设置请求参数
    		response = httpclient.execute(post);
    		// 判断网络连接状态码是否正常(0--200都数正常)
    		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    			String content = EntityUtils.toString(response.getEntity(), "UTF-8");
    			// 2.返回值为xml,使用DocumentHelper解析
    			Document parseText = DocumentHelper.parseText(content);
    			Element rootElement = parseText.getRootElement();
    			String code = rootElement.elementText("code");// 获取指定返回字段
    			String msg = rootElement.elementText("msg");
    			System.out.println("code:" + code + "------msg:" + msg);
    		}
    		EntityUtils.consume(response.getEntity());// 完全消耗
    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		try {
    			if (null != response)
    				response.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

四、HttpClient使用实例

package com.aiait.framework.action;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import net.sf.json.JSONObject;

/**
 * Created by zhenyu on 2018/6/26. 使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。 1.
 * 创建HttpClient对象。 2.
 * 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。 3.
 * 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams
 * params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。 4.
 * 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。 5.
 * 调用HttpResponse的getAllHeaders()、getHeaders(String
 * name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容
 * 。程序可通过该对象获取服务器的响应内容。 6. 释放连接。无论执行方法是否成功,都必须释放连接
 */
public class HttpClientUtil {
	// 配置请求参数(如果不配置则取默认值)
	private static RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)// 连接超时:connectionTimeout-->指的是连接一个url的连接等待时间
			.setSocketTimeout(5000)// 读取数据超时:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间
			.setConnectionRequestTimeout(5000)// 从连接池中获取到连接的最长时间
			.build();

	private static CloseableHttpClient getHttpClient() {
		// return
		// HttpClients.createDefault();//1.通过HttpClients获取,底层也是通过HttpClientBuilder工厂类获取
		return HttpClientBuilder.create().build();// 2.通过HttpClientBuilder工厂类获取
	}

	/**
	 * 无参get请求
	 * 
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doGet(String url) throws ClientProtocolException, IOException {
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(requestConfig);// 设置请求参数
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = getHttpClient().execute(httpGet);

			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				return content;
			}
		} finally {
			if (null != response)
				response.close();
			// httpclient.close();
		}
		return null;
	}

	/**
	 * 有参get请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws URISyntaxException
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doGet(String url, Map<String, String> params)
			throws URISyntaxException, ClientProtocolException, IOException {
		URIBuilder uriBuilder = new URIBuilder(url);
		if (params != null) {
			for (String key : params.keySet()) {
				uriBuilder.setParameter(key, params.get(key));
			}
		}
		return doGet(uriBuilder.build().toString());
	}

	/**
	 * 有参post请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPost(String url, Map<String, String> params) throws ClientProtocolException, IOException {
		// 创建http POST请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		if (params != null) {
			// 设置2个post参数,一个是scope、一个是q
			List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(0);
			for (String key : params.keySet()) {
				parameters.add(new BasicNameValuePair(key, params.get(key)));
			}
			// 构造一个form表单式的实体
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
			// 将请求实体设置到httpPost对象中
			httpPost.setEntity(formEntity);
		}
		CloseableHttpResponse response = null;
		String content = null;
		try {
			// 执行请求
			response = getHttpClient().execute(httpPost);
			// return new
			// HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),
			// "UTF-8"));
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				content = EntityUtils.toString(response.getEntity(), "UTF-8");
				// System.out.println(content);
			}
			return content;
		} finally {
			if (null != response)
				response.close();
			// httpclient.close();
		}
	}

	/**
	 * 有参post请求,json交互
	 * 
	 * @param url
	 * @param json
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPostJson(String url, String json) throws ClientProtocolException, IOException {
		// 创建http POST请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		if (StringUtils.isNotBlank(json)) {
			// 标识出传递的参数是 application/json
			StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(stringEntity);
		}
		CloseableHttpResponse response = null;
		String content = null;
		try {
			// 执行请求
			response = getHttpClient().execute(httpPost);
			// return new
			// HttpResult(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),
			// "UTF-8"));
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				content = EntityUtils.toString(response.getEntity(), "UTF-8");
				// System.out.println(content);
			}
			return content;
		} finally {
			if (null != response)
				response.close();
			// httpclient.close();
		}
	}

	/**
	 * 无参post请求
	 * 
	 * @param url
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPost(String url) throws ClientProtocolException, IOException {
		return doPost(url, null);
	}

	/**
	 * httpClient测试 1.ajax请求
	 * 当Ajax请求,Content-type:'application/x-www-form-urlencoded'(默认) + dataType :
	 * 'json',后台需要使用@RequestParam 或者request.getParameter获取参数。
	 * 当Ajax请求,Content-type:'application/json' +
	 * dataType:'json',后台需要使用@RquestBody获取参数。 2.httpClient请求
	 * 当参数类型为非json类型,则SpringMVC接口接收参数时可以直接使用@RequestParam
	 * 当参数类型为json类型,则需先通过StringEntity设置ContentType='application/json',
	 * 后台需要使用@RequesBody获取参数。
	 * 
	 */
	public static void main(String[] args) {

		// 测试接口地址
		String url = "http://localhost:9080/es-ext/webservice/generateNenewalMessage";

		// 测试参数
		List<BasicNameValuePair> urlParameters = new ArrayList<>();
		urlParameters.add(new BasicNameValuePair("username", "zhangsan"));
		urlParameters.add(new BasicNameValuePair("password", "123456"));

		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("username", "zhangsan");
		parameters.put("password", "123456");

		// String params =
		// "{\"username\":\"zhangsan\",\"password\":\"123456\"}";
		JSONObject json = new JSONObject();
		json.put("username", "zhangsan");
		json.put("password", "123456");

		// 测试
		/*
		 * try {
		 * 
		 * //1.get请求测试 String doGet = doGet(url, parameters);
		 * System.out.println("doGet--------"+doGet); //2.post请求测试 String doPost
		 * = doPost(url, parameters);
		 * System.out.println("doPost--------"+doPost); //3.postjson请求测试 String
		 * doPostjson = doPostJson(url, json.toString());
		 * System.out.println("doPostjson--------"+doPostjson);
		 * 
		 * } catch (Exception e) { e.printStackTrace(); }
		 */

		// 4.自定义post请求测试
		CloseableHttpClient httpclient = HttpClients.createDefault();// HttpClient,
																		// Closeable的实现类,可实现自动close
		CloseableHttpResponse response = null;
		HttpPost post = new HttpPost(url);
		try {
			post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));// 设置post请求的参数
			post.setConfig(requestConfig); // 设置请求参数
			response = httpclient.execute(post);
			// 判断网络连接状态码是否正常(0--200都数正常)
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				// 1.返回值为json
				JSONObject jsonObject = JSONObject.fromObject(content);
				System.out.println(jsonObject.getString("code") + ":" + jsonObject.getString("msg"));
				// 2.返回值为xml
				/*
				 * Document parseText = DocumentHelper.parseText(content);
				 * Element rootElement = parseText.getRootElement(); 
				 * String code = rootElement.elementText("code");//获取指定返回字段 
				 * String msg = rootElement.elementText("msg");
				 * System.out.println("code:"+code+"------msg:"+msg);
				 */
			}
			EntityUtils.consume(response.getEntity());// 完全消耗
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != response)
					response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值