【Java】HTTP请求工具类

这篇具有很好参考价值的文章主要介绍了【Java】HTTP请求工具类。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

在工作中可能存在要去调用其他项目的接口,这篇文章我们实现在Java代码中实现调用其他项目的接口。

本章内容:
创建一个携带参数的POST请求,去请求其他项目的接口并返回数据。
附加HTTP请求工具类,包含(GET、POST、无参GET、无参POST)

准备

导入pom依赖

	<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore -->
   <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpcore</artifactId>
   </dependency>
   <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
   <dependency>
       <groupId>org.apache.httpcomponents</groupId>
       <artifactId>httpclient</artifactId>
   </dependency>
   <!--json工具-->
	<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
    </dependency>

案例

创建一个携带参数的POST请求

public static String doPost(String url, String str, String encoding) {
    String body = "";
     try {
         // 创建httpclient对象
         CloseableHttpClient client = HttpClients.createDefault();
         // 创建post方式请求对象
         HttpPost httpPost = new HttpPost(url);
         // 设置参数到请求对象中
         httpPost.setEntity(new StringEntity(str, encoding));
         // 设置header信息
         // 指定报文头【Content-type】、【User-Agent】
         httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
         // 执行请求操作,并拿到结果(同步阻塞)
         CloseableHttpResponse response = client.execute(httpPost);
         // 获取结果实体
         HttpEntity entity = response.getEntity();
         if (entity != null) {
             // 按指定编码转换结果实体为String类型
             body = EntityUtils.toString(entity, encoding);
         }
         EntityUtils.consume(entity);
         // 释放链接
         response.close();
         return body;
     } catch (Exception e1) {
         e1.printStackTrace();
         return "";

     }
 }

参数列表:

  • url:请求的接口地址(例:http://IP地址:8080/user/login
  • str:发送请求时候携带的参数(必须为JSON格式的字符串
  • encoding:编码字符集(一般都为UTF-8

通过调用doPost()可以接受一个返回值,返回值的类型是String类型的JSON字符串,通过fastjson工具进行转换在进行其他业务操作。

测试

JSONObject json= new JSONObject();
json.put("id", "10010");
json.put("name", "蔡徐坤");

String url = "http://IP地址:8080/user/login";
String encoding = "UTF-8";

String result = doPost(url, json.toString(), encoding);
logger.info("请求地址返回的数据为 = {}", result);

返回结果:文章来源地址https://www.toymoban.com/news/detail-519611.html

{code : 500, msg: "登录失败"}

完整的HTTP请求工具类

public class HttpClientUtil {
	
	/**
	 * 带参数的get请求
	 * @param url
	 * @param param
	 * @return String
	 */
	public static String doGet(String url, Map<String, String> param) {
		// 创建Httpclient对象
		if(url==null||"".equals(url))
			return null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
 
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	
	/**
	 * 不带参数的get请求
	 * @param url
	 * @return String
	 */
	public static String doGet(String url) {
		return doGet(url, null);
	}
	
	public static String doGetByHeader(String url, String orgKey) {
		// 创建Httpclient对象
		if(url==null||"".equals(url))
			return null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
 
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			httpGet.addHeader("Org-Key", orgKey);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
 
	/**
	 * 带参数的post请求
	 * @param url
	 * @param param
	 * @return String
	 */
	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			httpPost.addHeader("Content-Type","application/json; charset=utf-8");
			httpPost.addHeader("X-Api-Sign-Version","2.0.0");
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
//				httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
//				httpPost.setEntity(new StringEntity(str, encoding));
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
 
	/**
	 * 不带参数的post请求
	 * @param url
	 * @return String
	 */
	public static String doPost(String url) {
		return doPost(url, null);
	}
	
	/**
	 * 传送json类型的post请求
	 * @param url
	 * @param json
	 * @return String
	 */
	public static String doPostJson(String url, String json, String token) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			if(url.contains("?")){
				url = url + "&access_token=" + token;
			} else {
				url = url + "?access_token=" + token;
			}
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			//httpPost.addHeader("Org-Key", orgKey);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

}

到了这里,关于【Java】HTTP请求工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • java使用hutool工具类发送http或者https请求太香啦

    我们使用java内置的http工具实现远程调用的时候,都是用try catch包一堆代码,巨难受,今天看见有人使用hutool工具类那是天简单了呀,具体操作如下: 1,引入依赖 2, 如果不需要设置其他什么头信息,代码: 如果是https请求直接换url里面的http就行 返回信息格式: {\\\"code\\\":200

    2024年02月14日
    浏览(27)
  • java 通过HTTP接收json

    一: json接收类, 第一个接口为直接传参接收 第二个接口接收json字符串 可以写个HTTP测试类调用测试,也可以postman测试调用,实例方法贴到下面 二:HTTP工具类 三:Test测试类

    2024年02月16日
    浏览(27)
  • java发送Http请求

    使用java 11添加的HttpClient新API发送Http(Https)请求 HTTP客户端是在Java 11中添加的。它可以用于通过网络请求HTTP资源。它支持 HTTP / 1.1和HTTP / 2(同步和异步编程模型),将请求和响应主体作为反应流处理,并遵循熟悉的构建器模式。 参考文章:https://blog.csdn.net/allway2/article/detail

    2023年04月12日
    浏览(33)
  • Java http 接口请求

    2024年02月11日
    浏览(34)
  • 用java发送http请求

    在 Java 中发送 HTTP 请求可以使用标准的 Java 库或者第三方库。这里介绍使用 Java 标准库中的 HttpURLConnection 类来发送 HTTP 请求的方法: 首先,使用 URL 类来创建一个 URL 对象,指定要访问的 URL。 使用 URL 对象的 openConnection 方法来获取 HttpURLConnection 对象。 设置 HTTP 请求的方法

    2024年02月16日
    浏览(33)
  • Java中的HTTP POST请求

    Java中的HTTP POST请求 在Java中,我们经常需要使用HTTP协议进行网络通信。其中,POST请求是一种常用的方式,它允许我们向服务器发送数据并获取响应。本文将介绍如何在Java中发送HTTP POST请求,并提供相应的源代码示例。 首先,我们需要导入Java标准库中的相关类和接口。在J

    2024年02月07日
    浏览(24)
  • java中几种http请求方式

    在Java中,发送HTTP请求的方式主要有以下几种: 使用 java.net.HttpURLConnection 类: HttpURLConnection是Java中用于发送HTTP请求和接收HTTP响应的类。它是java.net包中的一部分,基于Java的网络编程API。 HttpURLConnection的一些常用参数和方法如下: 优点:这是Java标准库提供的方法,不需要额

    2024年02月05日
    浏览(29)
  • Java中实现http请求的方式

    在java开发中,经常遇到需要调用第三方提供的接口服务的需求,下面对实现http请求的方式进行浅入浅析并进行实例尝试。若是普通java工程推荐使用OkHttpClient,若是spring工程推荐使用RestTemplate。 在java开发中,实现访问第三方接口服务的常见方式: 通过JDK类 Java.net.HttpURLConn

    2024年01月23日
    浏览(28)
  • Java Http各个请求类型详细介绍

    在Spring Boot框架中,HTTP请求类型是构建Web应用程序的重要组成部分。常见的请求类型包括GET、POST、PUT和DELETE,每种类型都有其特定的用途和特点。本文将详细比较这四种请求类型,帮助您在开发过程中做出明智的选择。 GET请求是最常见的请求类型,主要用于从服务器检索数

    2024年02月02日
    浏览(24)
  • java http请求设置代理 Proxy

    有如下一种需求,原本A要给C发送请求,但是因为网络原因,需要借助B才能实现,所以由原本的A-C变成了A-B-C。 这种情况,更多的见于内网请求由统一的网关做代理然后转发出去,比如你本地的机器想要对外上网,都是通过运营商给的出口IP也就是公网地址实现的。这种做法

    2024年02月11日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包