首页 > 其他分享 >HttpClient和OkHttp发送http请求

HttpClient和OkHttp发送http请求

时间:2022-10-09 12:02:54浏览次数:53  
标签:http String apache org OkHttp import HttpClient response httpClient


根据技术选型总结常见的三种方式发送http请求,本问介绍框架中常用的HttpClient和OkHttp方式,其他两种如下链接

​springboot中使用restTemplate发送http请求​​ 

一、httpclient

1、直接使用apache的HttpClient开发

使用方便,但依赖于第三方jar包,相关maven依赖如下:

<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency

简单测试

package httpClient;

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientHelper {
public static String sendPost(String urlParam) throws HttpException, IOException {
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建post请求方法实例对象
PostMethod postMethod = new PostMethod(urlParam);
// 设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");

httpClient.executeMethod(postMethod);

String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
return result;
}
public static String sendGet(String urlParam) throws HttpException, IOException {
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建GET请求方法实例对象
GetMethod getMethod = new GetMethod(urlParam);
// 设置post请求超时时间
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
getMethod.addRequestHeader("Content-Type", "application/json");

httpClient.executeMethod(getMethod);

String result = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
return result;
}
public static void main(String[] args) throws HttpException, IOException {
String url ="http://int.dpool.sina.com.cn/iplookup/iplookup.php?ip=120.79.75.96";
System.out.println(sendPost(url));
System.out.println(sendGet(url));
}
}

比较全的工具类

导入jar

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.IOException;

public class HttpClientUtil {
/**
* httpClient的get请求方式
* 使用GetMethod来访问一个URL对应的网页实现步骤:
* 1.生成一个HttpClient对象并设置相应的参数;
* 2.生成一个GetMethod对象并设置响应的参数;
* 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
* 4.处理响应状态码;
* 5.若响应正常,处理HTTP响应内容;
* 6.释放连接。
* @param url
* @param charset
* @return
*/
public static String doGet(String url, String charset) {
//1.生成HttpClient对象并设置参数
HttpClient httpClient = new HttpClient();
//设置Http连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
//2.生成GetMethod对象并设置参数
GetMethod getMethod = new GetMethod(url);
//设置get请求超时为5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
//3.执行HTTP GET 请求
try {
int statusCode = httpClient.executeMethod(getMethod);
//4.判断访问的状态码
if (statusCode != HttpStatus.SC_OK) {
System.err.println("请求出错:" + getMethod.getStatusLine());
}
//5.处理HTTP响应内容
//HTTP响应头部信息,这里简单打印
Header[] headers = getMethod.getResponseHeaders();
for(Header h : headers) {
System.out.println(h.getName() + "---------------" + h.getValue());
}
//读取HTTP响应内容,这里简单打印网页内容
//读取为字节数组
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, charset);
System.out.println("-----------response:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e) {
//发生网络异常
System.out.println("发生网络异常!");
} finally {
//6.释放连接
getMethod.releaseConnection();
}
return response;
}

/**
* post请求
* @param url
* @param json
* @return
*/
public static String doPost(String url, JSONObject json){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);

postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");
//必须设置下面这个Header
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//添加请求参数
postMethod.addParameter("commentId", json.getString("commentId"));

String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
res = postMethod.getResponseBodyAsString();
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}

public static void main(String[] args) {
System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));
System.out.println("-----------分割线------------");
System.out.println("-----------分割线------------");
System.out.println("-----------分割线------------");

JSONObject jsonObject = new JSONObject();
jsonObject.put("commentId", "13026194071");
System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));
}
}

2、通过Apache封装好的CloseableHttpClient

CloseableHttpClient是在HttpClient的基础上修改更新而来的,这里还涉及到请求头token的设置(请求验证),利用fastjson转换请求或返回结果字符串为json格式,当然上面两种方式也是可以设置请求头token、json的,这里只在下面说明。

<!--CloseableHttpClient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>

<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.32</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class CloseableHttpClientUtil {

private static String tokenString = "";
private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
private static CloseableHttpClient httpClient = null;

/**
* 以get方式调用第三方接口
* @param url
* @param token
* @return
*/
public static String doGet(String url, String token) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
if (null != tokenString && !tokenString.equals("")) {
tokenString = getToken();
}
//api_gateway_auth_token自定义header头,用于token验证使用
httpGet.addHeader("api_gateway_auth_token",tokenString);
httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
try {
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 以post方式调用第三方接口
* @param url
* @param json
* @return
*/
public static String doPost(String url, JSONObject json) {
if (null == httpClient) {
httpClient = HttpClientBuilder.create().build();
}
HttpPost httpPost = new HttpPost(url);
if (null != tokenString && tokenString.equals("")) {
tokenString = getToken();
}
//api_gateway_auth_token自定义header头,用于token验证使用
httpPost.addHeader("api_gateway_auth_token", tokenString);
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
try {
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
se.setContentType("application/x-www-form-urlencoded");
//设置请求参数
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//返回json格式
String res = EntityUtils.toString(response.getEntity());
return res;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

/**
* 获取第三方接口的token
*/
public static String getToken() {
String token = "";
JSONObject object = new JSONObject();
object.put("appid", "appid");
object.put("secretkey", "secretkey");
if (null == httpClient) {
httpClient = HttpClientBuilder.create().build();
}
HttpPost httpPost = new HttpPost("http://localhost/login");
httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
try {
StringEntity se = new StringEntity(object.toString());
se.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
se.setContentType("application/x-www-form-urlencoded");
//设置请求参数
httpPost.setEntity(se);
HttpResponse response = httpClient.execute(httpPost);
//这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
//ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
//把response转为jsonObject
JSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));
if (result.containsKey("token")) {
token = result.getString("token");
}
} catch (IOException e) {
e.printStackTrace();
}
return token;
}

/**
* 测试
*/
public static void test(String telephone) {

JSONObject object = new JSONObject();
object.put("telephone", telephone);

//首先获取token
tokenString = getToken();
String response = doPost("http://localhost/searchUrl", object);
//如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
//List<Result> list = JSONObject.parseArray(response, Result.class);
System.out.println(response);
}

public static void main(String[] args) {
test("12345678910");
}
}

二、okhttp

引入依赖

<dependency>

<groupId>com.squareup.okhttp3</groupId>

<artifactId>okhttp</artifactId>

<version>3.10.0</version>

</dependency>

 参考文章

​HTTP连接客户端,选 HttpClient 还是 OkHttp ?_Java技术头条的博客​

标签:http,String,apache,org,OkHttp,import,HttpClient,response,httpClient
From: https://blog.51cto.com/u_11334685/5740084

相关文章

  • java原生发送http请求
    根据技术选型总结常见的三种方式发送http请求,本问介绍jdk原生方式,其他两种如下链接​​httpclient和okhttp​​​​Springboot整合RestTemplate发送http请求​​使用JDK原生......
  • SOCK5代理服务器与HTTP代理有什么区别?
    SOCKS5代理与HTTP代理的区别:SOCKS工作在比HTTP代理更低的层次:SOCKS使用握手协议来通知代理软件其客户端试图进行的连接SOCKS,然后尽可能透明地进行操作,而常规代理可能会......
  • 华科云商HTTP代理什么意思
    在进行网页爬虫的时候使用HTTP代理,可以进行匿名抓取网页信息,爬取大数据等使用方向。HTTP代理我们很。HTTP协议即超文本传输协议,是Internet上信息传输时使用最为广泛的一种简......
  • HTTP协议有必要学习吗?
    自从有了互联网,网站WEB编程成了高校计算机专业的一门专业课。Java、HTML、CSS、JS、MySQL、JSP、Servlet,这些知识点点点滴滴累计起来,可以创建出一个非常绚丽多彩的网站......
  • Java服务发起HTTPS请求报错:PKIX path building failed: sun.security.provider.certpa
    Java服务发起HTTPS请求报错:PKIXpathbuildingfailed:sun.security.provider.certpath.SunCertPathBuilderException1.从域名的https导出下载证书文件下载证书第一步是......
  • nginx安装https模块失败
    问题描述在执行命令 ./configure--prefix=/usr/local/nginx --with-http_ssl_module报如下错误./configure:error:SSLmodulesrequiretheOpenSSLlibrary.Y......
  • https://github.com/succlz123/AcFun-Client-Multiplatform
    GitHub-succlz123/AcFun-Client-Multiplatform:Athirdpartmultipaltformclientofhttps://www.acfun.cn/.Thegoalofthisrepositoryistobuildaonlinemed......
  • Consul的HTTP API和使用方法
    Consul支持基础结构的服务注册和发现(称为内部服务),也支持外部服务(第三方SAAS服务以及无法直接运行Consul代理的其它环境,例如redis)。直接使用sudoapt-getinstallc......
  • 漏洞修复:tomcat中间件修复 检测到目标URL存在http host头攻击漏洞
    漏洞名称:检测到目标URL存在httphost头攻击漏洞风险级别:中危修复方案:修改tomcat\conf\server.xml打开server.xml配置文件,找到如下配置:  将Host里name的值localhost......
  • Java如何调用HttpURLConnection类模拟浏览器访问呢?
    下文笔者讲述使用Java代码模拟浏览器请求的方法分享,如下所示:实现思路:使用HttpURLConnection类即可模拟浏览器访问例:packagecom.java265.other;importjava.......