使用Java通过HttpClient发送HTTP请求

  • 1.HttpClient介绍
  • 2.HttpClient的使用-流程说明
  • 2.HttpClient的使用-代码
  • 1.依赖
  • 2. 发送get请求
  • 3. 发送post请求
  • 3. 获取登录的cookie
  • 4. 带cookie访问接口


前言:在目前的一个项目中,我们的项目的数据来源内部的一个完善的移动端系统,想要集成他们系统的数据就得使用Java发送http模拟前端请求他们的接口,由此在项目中使用HttpClient来发送请求访问接口,此篇记录使用HttpClient的心得。

1.HttpClient介绍

HttpClient是Apache提供的一个用于在Java中处理HTTP请求、响应操作的工具,它不是一个浏览器只是一个客户端的 HTTP 通信实现库。HttpClient的目标是发送请求和接收HTTP 报文,它不会去缓存内容和执行内嵌的js代码等相应的浏览器的功能。

2.HttpClient的使用-流程说明

第一步:使用CloseableHttpClient来创建一个httpClient对象。
第二步:声明请求类型,并传入相应的URL。
第三步:使用httpClient的excute()方法来传递请求对象,并获取响应对象。
第四步:获取服务器的状态码,并判断该状态码是否正常。
第五步:正常的话则将服务器发送的数据封装成HttpEntity对象。
第六步:将所得对象转化成字符串。
第七步:关闭连接,释放资源。

2.HttpClient的使用-代码

1.依赖

jar包:

java 请求接口的ip和端口 http请求 java_java


ps:需要引入3个主要jar包,httpclient-cache可以不引入。

maven:

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient-cache</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.2.2</version>
        </dependency>

2. 发送get请求

PS:代码仅提供参考,需根据业务情况进行修改代码。

public static String getNeedApprove(String appId,String appPassword,String account) {
		String result = "";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse res = null;
		try {

			HttpClientContext context = HttpClientContext.create();
			// 创建一个httpClient对象
			httpclient = HttpClients.createDefault();
			//登陆 从配置文件中读取url(也可以写成参数)
			HttpGet httpGet = new HttpGet(Constants.APPLOGIN); 
			// 设置参数
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("xxx", appId));
			formparams.add(new BasicNameValuePair("xxx", appPassword));
			formparams.add(new BasicNameValuePair("xxx", account));
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httpGet.setEntity(uefEntity);
			// 得到响应状态码
			res = httpclient.execute(httpGet,context);
			//  获取返回对象
			HttpEntity entity = res.getEntity();
			// 通过EntityUtils获取返回结果内容
			result = EntityUtils.toString(entity);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//  最后一定要释放资源
			if(httpclient!=null) {
				try {
					httpclient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}

3. 发送post请求

PS:代码仅提供参考,需根据业务情况进行修改代码。

public static String postNeedApprove(String Id,String Password,String account) {
		String result = "";
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse res = null;
		try {

			HttpClientContext context = HttpClientContext.create();
			// 创建一个httpClient对象
			httpclient = HttpClients.createDefault();
			//登陆 从配置文件中读取url(也可以写成参数)
			HttpPost httpPost = new HttpPost(Constants.APPLOGIN); 
			// 设置参数
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("xxx", Id));
			formparams.add(new BasicNameValuePair("xxx", Password));
			formparams.add(new BasicNameValuePair("xxx", account));
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httpPost.setEntity(uefEntity);
			// 得到响应状态码
			res = httpclient.execute(httpPost,context);
			//  获取返回对象
			HttpEntity entity = res.getEntity();
			// 通过EntityUtils获取返回结果内容
			result = EntityUtils.toString(entity);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//  最后一定要释放资源
			if(httpclient!=null) {
				try {
					httpclient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		return result;
	}

3. 获取登录的cookie

PS:代码仅提供参考,需根据业务情况进行修改代码。

public static String getCookie(String account) {
		String mpApi = "";
		// 创建存储cookie的空间
		CookieStore store = new BasicCookieStore();
		CloseableHttpClient httpclient = null;
		HttpPost httppost = null;
		try {
			httpclient = HttpClients.custom().setDefaultCookieStore(store).build();// 设置超时时间
			// 登陆
			httppost = new HttpPost(CommonVar.APPLOGIN); // 测试环境
			// 设置请求需传参数
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			formparams.add(new BasicNameValuePair("xxx", CommonVar.ID));
			formparams.add(new BasicNameValuePair("xxx", CommonVar.PASSWORD));
			formparams.add(new BasicNameValuePair("xxx", account));
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
			// 获取响应的cookie
			CloseableHttpResponse res = httpclient.execute(httppost);
			// 遍历cookie存储store
			for (Iterator iterator = store.getCookies().iterator(); iterator.hasNext();) {
				Cookie cookie = (Cookie) iterator.next();
				System.out.println(cookie.getName() + "," + cookie.getValue());
				if (cookie.getName().equals("mpApi")) {
					mpApi = cookie.getValue();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return mpApi;
	}

4. 带cookie访问接口

PS:代码仅提供参考,需根据业务情况进行修改代码。

public static String queryUser(HttpServletRequest request, String account, String cookie) {
		String result = "";
		CloseableHttpClient httpclient = null;
		HttpPost httppost = null;
		try {
			// 将获取的cookie放入CloseableHttpClient中
			httpclient = getHttpClient(cookie);
			List<NameValuePair> detailparams = new ArrayList<NameValuePair>();
			detailparams.add(new BasicNameValuePair("xxx", account));
			UrlEncodedFormEntity detailEntity = new UrlEncodedFormEntity(detailparams, "UTF-8");
			httppost = new HttpPost(CommonVar.QUERYUSER);
			httppost.setHeader("Id", CommonVar.ID);
			httppost.setEntity(detailEntity);
			CloseableHttpResponse res = httpclient.execute(httppost);
			HttpEntity entity = res.getEntity();
			result = EntityUtils.toString(entity);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}