Java后端常用的4种请求方式(通俗易懂)

news/2025/1/8 17:44:09/
http://www.w3.org/2000/svg" style="display: none;">

文章目录

  • 前言
      • 通用接口类(ControllerDemo)
      • 通用实体类(UserEntity)
      • 通用响应类(HttpClientResult)
      • 成功截图(先启动项目,然后右键执行main方法)
  • HttpClient
    • HttpClient 的主要类
    • 代码案例
      • 导入依赖
      • 工具类(HttpClientUtil)
      • 测试类
  • HttpURLConnection
    • 简介
    • 调用步骤
    • 代码案例
      • 导入依赖
      • 工具类(HttpURLConnectionUtil)
      • 测试类(HttpURLConnectionDemo)
  • OkHttp
    • 简介
    • 调用步骤
    • 代码案例
      • 引入依赖
      • 工具类(OkHttpUtil)
      • 测试类
  • RestTemplate
    • 简介
    • 代码案例
      • 测试类(RestTemplateDemo)

前言

Java中HTTP的4中请求方式,每个都有工具类,都可以直接使用,亲测可用
案例中使用的springBoot结构,JDK8,需要web模块,所以需要引入web依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId>
</dependency>

通用接口类(ControllerDemo)

java">import org.springframework.web.bind.annotation.*;/*** @author yj*/
@RestController
public class ControllerDemo {@GetMapping("/get")public String get(){return "get OK";}@GetMapping("/getById")public String getById(String id){return "getById OK:"+id;}@PostMapping("/query")public String query(){return "query OK";}@PostMapping("/queryByUser")public String querByUser(@RequestBody UserEntity user){return "queryByUser OK:"+user.toString();}
}

通用实体类(UserEntity)

java">@Data
@ToString
@Accessors(chain = true)
public class UserEntity {String name;int age;String sex;
}

通用响应类(HttpClientResult)

java">import java.io.Serializable;/*** @author yj*/
public class HttpResult implements Serializable {private static final long serialVersionUID = -7444139462774166373L;//响应状态码private int code;//响应数据private String content;public HttpClientResult(int code, String content) {this.code = code;this.content = content;}public HttpClientResult(int code) {this.code = code;}
}

成功截图(先启动项目,然后右键执行main方法)

https://i-blog.csdnimg.cn/direct/c5d09818edd44906b2c40f44142a05de.png" alt="在这里插入图片描述" />

HttpClient

HttpClient 的主要类

HttpClient是用于发送HTTP请求和处理HTTP响应的主要类。它提供了一种简单且一致的方式来执行HTTP操作,包括同步和异步的请求发送、连接池管理、请求和响应的拦截器等功能。

HttpRequest是用于表示HTTP请求的类。通过HttpRequest对象,您可以设置请求的URL、请求方法、请求头、请求体等信息,并构建一个完整的HTTP请求对象,用于发送给服务器。

HttpResponse是用于表示HTTP响应的类。当客户端发送HTTP请求后,服务器会返回一个HTTP响应,HttpResponse对象用于表示这个响应。通过HttpResponse对象,您可以获取响应的状态码、响应头、响应体等信息,以便进一步处理响应。

代码案例

本案例使用springBoot项目,JDK8,网上说11之后会有所不同,之后再研究

导入依赖

<!-- Apache HttpClient依赖 -->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version>
</dependency>

工具类(HttpClientUtil)

java">import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
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.HttpClients;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.util.Map;
import java.util.Set;/*** @author YJ*/
public class HttpClientUtil {// 编码格式。发送编码格式统一用UTF-8private static final String ENCODING = "UTF-8";// 设置连接超时时间,单位毫秒。private static final int CONNECT_TIMEOUT = 6000;// 请求获取数据的超时时间(即响应时间),单位毫秒。private static final int SOCKET_TIMEOUT = 6000;/*** 发送get请求;不带请求头和请求参数** @param url 请求地址*/public static HttpResult doGet(String url) throws Exception {return doGet(url, null, null);}/*** 发送get请求;带请求参数** @param url    请求地址* @param params 请求参数集合*/public static HttpResult doGet(String url, Map<String, String> params) throws Exception {return doGet(url, null, params);}/*** 发送get请求;带请求头和请求参数** @param url     请求地址* @param headers 请求头集合* @param params  请求参数集合*/public static HttpResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {// 创建httpClient对象CloseableHttpClient httpClient = HttpClients.createDefault();// 创建访问的地址URIBuilder uriBuilder = new URIBuilder(url);if (params != null) {Set<Map.Entry<String, String>> entrySet = params.entrySet();for (Map.Entry<String, String> entry : entrySet) {uriBuilder.setParameter(entry.getKey(), entry.getValue());}}// 创建http对象HttpGet httpGet = new HttpGet(uriBuilder.build());
//        /**
//         * setConnectTimeout:设置连接超时时间,单位毫秒。
//         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
//         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
//         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
//         */RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();httpGet.setConfig(requestConfig);// 设置请求头packageHeader(headers, httpGet);// 创建httpResponse对象CloseableHttpResponse httpResponse = null;try {// 执行请求并获得响应结果return getResult(httpClient, httpGet);} finally {// 释放资源release(httpResponse, httpClient);}}/*** 发送post请求;不带请求头和请求参数** @param url 请求地址*/public static HttpResult doPost(String url) throws Exception {return doPost(url, null, null);}/*** 发送post请求;带请求参数** @param url    请求地址*/public static HttpResult doPost(String url, String jsonString) throws Exception {return doPost(url, null, jsonString);}/*** 发送post请求;带请求头和请求参数** @param url     请求地址* @param headers 请求头集合*/public static HttpResult doPost(String url, Map<String, String> headers, String jsonString) throws Exception {// 创建httpClient对象CloseableHttpClient httpClient = HttpClients.createDefault();// 创建http对象HttpPost httpPost = new HttpPost(url);
//        /**
//         * setConnectTimeout:设置连接超时时间,单位毫秒。
//         * setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
//         * 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
//         * setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
//         */RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();httpPost.setConfig(requestConfig);// 设置请求头/*httpPost.setHeader("Cookie", "");httpPost.setHeader("Connection", "keep-alive");httpPost.setHeader("Accept", "application/json");httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/packageHeader(headers, httpPost);// 封装请求参数packageParam(jsonString, httpPost);// 创建httpResponse对象CloseableHttpResponse httpResponse = null;try {// 执行请求并获得响应结果return getResult(httpClient, httpPost);} finally {// 释放资源release(httpResponse, httpClient);}}/*** Description: 封装请求头*/private static void packageHeader(Map<String, String> headers, HttpRequestBase httpMethod) {// 封装请求头if (headers != null) {Set<Map.Entry<String, String>> entrySet = headers.entrySet();for (Map.Entry<String, String> entry : entrySet) {// 设置到请求头到HttpRequestBase对象中httpMethod.setHeader(entry.getKey(), entry.getValue());}}}/*** Description: 封装请求参数*/private static void packageParam(String jsonString, HttpEntityEnclosingRequestBase httpMethod) {// 封装请求参数if (jsonString != null) {// 设置到请求的http对象中httpMethod.setEntity(new StringEntity(jsonString, ContentType.APPLICATION_JSON));}}/*** Description: 获得响应结果*/private static HttpResult getResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {// 执行请求CloseableHttpResponse httpResponse = httpClient.execute(httpMethod);// 获取返回结果if (httpResponse != null && httpResponse.getStatusLine() != null) {String content = "";if (httpResponse.getEntity() != null) {content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);}return new HttpResult(httpResponse.getStatusLine().getStatusCode(), content);}return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);}/*** Description: 释放资源*/private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {// 释放资源if (httpResponse != null) {httpResponse.close();}if (httpClient != null) {httpClient.close();}}
}

测试类

java">import com.baicaizhi.utils.HttpClientUtil;
import com.baicaizhi.utils.HttpResult;
import com.google.gson.Gson;import java.util.HashMap;
import java.util.Map;/**** @author yj**/
public class HttpClientDemo {public static void main(String[] args) throws Exception {String getUrl = "http://localhost:8080/get";String getByIdUrl = "http://localhost:8080/getById";String query = "http://localhost:8080/query";String queryByUser = "http://localhost:8080/queryByUser";//不带参数getHttpResult httpResult = HttpClientUtil.doGet(getUrl);System.out.println(httpResult.toString());//带参数getMap<String, String> params = new HashMap<String, String>();params.put("id", "123456789");HttpResult httpResult1 = HttpClientUtil.doGet(getByIdUrl, params);System.out.println(httpResult1.toString());//不带参数PostHttpResult httpResult2 = HttpClientUtil.doPost(query);System.out.println(httpResult2.toString());//带参数PostMap<String, String> user = new HashMap<String, String>();user.put("age", "22");user.put("name", "yj");user.put("sex","男");HttpResult httpResult3 = HttpClientUtil.doPost(queryByUser, new Gson().toJson(user));System.out.println(httpResult3.toString());}
}

HttpURLConnection

简介

HttpURLConnection一个抽象类是标准的JAVA接口,该类位于java.net包中,它提供了基本的URL请求,响应等功能。

HttpURLConnection是基于http协议的,支持GET、POST、PUT、DELETE等各种请求方式。如果使用HTTPS协议请求,可以使用它的子类HttpsURLConnection完成更安全的请求操作。

调用步骤

  1. 创建一个URL对象:URL url=new URL(“接口地址”)
  2. 调用URL对象的openConnection()来获取HttpURLConnection对象实例;
    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
  3. 设置HTTP请求使用的方法:GET、POST或其他请求;
    connection.setRequestMethod(“GET”);
  4. 设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头;
    connection.setConnectTimeout(6*1000);
    connection.setReadTimeout(6 * 1000);
  5. 调用getInputStream()方法获得服务器返回的输入流,然后输入流进行读取了;
    InputStream in = connection.getInputStream();
  6. 最后调用disconnect()方法将HTTP连接关掉;
    connection.disconnect();

代码案例

导入依赖

本工具类中使用到了Gson,所以需要导入一下依赖

<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId>
</dependency>

工具类(HttpURLConnectionUtil)

java">import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpStatus;
import tk.mybatis.mapper.util.StringUtil;import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import java.util.StringJoiner;/*** @author YJ*/
public class HttpURLConnectionUtil {// 编码格式。发送编码格式统一用UTF-8private static final String ENCODING = "UTF-8";// 设置连接超时时间,单位毫秒。private static final int CONNECT_TIMEOUT = 6000;// 请求获取数据的超时时间(即响应时间),单位毫秒。private static final int SOCKET_TIMEOUT = 6000;/*** 发送get请求;不带请求头和请求参数** @param httpUrl 请求地址*/public static HttpResult doGet(String httpUrl) throws Exception {return doGet(httpUrl, null, null);}/*** 发送get请求;带请求参数** @param httpUrl    请求地址* @param jsonString 请求参数集合*/public static HttpResult doGet(String httpUrl, String jsonString) throws Exception {return doGet(httpUrl, null, jsonString);}/*** 发送get请求;带请求头和请求参数** @param httpUrl    请求地址* @param headers    请求头集合* @param jsonString json字符串*/public static HttpResult doGet(String httpUrl, Map<String, String> headers, String jsonString) throws Exception {HttpURLConnection connection = null;InputStream is = null;OutputStream os = null;BufferedReader br = null;if (StringUtil.isNotEmpty(jsonString)) {//将JSON字符串转成MapMap<String, String> map = new Gson().fromJson(jsonString, new TypeToken<Map<String, String>>() {}.getType());//将map转成成String "id"=123&""name"="yj"String queryString = convertToQueryString(map);httpUrl = httpUrl + "?" + queryString;}//打开请求connection = openConn(httpUrl);//设置请求头packageHeader("GET", headers, connection);// 通过连接对象获取一个输入流,向远程读取return getResult(connection, is, os, br, null);}/*** 发送post请求;不带请求头和请求参数** @param url 请求地址*/public static HttpResult doPost(String url) throws Exception {return doPost(url, null, null);}/*** 发送post请求;带请求参数** @param url        请求地址* @param jsonString json字符串*/public static HttpResult doPost(String url, String jsonString) throws Exception {return doPost(url, null, jsonString);}/*** 发送post请求;带请求头和请求参数** @param httpUrl    请求地址* @param headers    请求头集合* @param jsonString json字符串*/public static HttpResult doPost(String httpUrl, Map<String, String> headers, String jsonString) throws Exception {HttpURLConnection connection = null;InputStream is = null;OutputStream os = null;BufferedReader br = null;String result = null;// 通过远程url连接对象打开连接connection = openConn(httpUrl);//设置请求头packageHeader("POST", headers, connection);// 通过连接对象获取一个输入流,向远程读取return getResult(connection, is, os, br, jsonString);}/*** Description: 打开连接*/private static HttpURLConnection openConn(String httpUrl) throws Exception {// 创建远程url连接对象URL url = new URL(httpUrl);// 通过远程url连接对象打开连接return (HttpURLConnection) url.openConnection();}/*** Description: 封装请求头*/private static void packageHeader(String method, Map<String, String> headers, HttpURLConnection connection) throws Exception {// 设置连接请求方式connection.setRequestMethod(method);// 设置连接主机服务器超时时间:15000毫秒connection.setConnectTimeout(CONNECT_TIMEOUT);// 设置读取主机服务器返回数据超时时间:60000毫秒connection.setReadTimeout(SOCKET_TIMEOUT);// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为trueconnection.setDoOutput(true);// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无connection.setDoInput(true);// 封装请求头if (headers != null) {Set<Map.Entry<String, String>> entrySet = headers.entrySet();for (Map.Entry<String, String> entry : entrySet) {// 设置到请求头到HttpRequestBase对象中connection.setRequestProperty(entry.getKey(), entry.getValue());}}}/*** Description: 获得响应结果*/private static HttpResult getResult(HttpURLConnection connection,InputStream is, OutputStream os, BufferedReader br, String jsonString) throws Exception {try {//如果为空直接发送请求if (StringUtil.isEmpty(jsonString)) {//发送请求connection.connect();} else {// 通过连接对象获取一个输出流os = connection.getOutputStream();// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的os.write(jsonString.getBytes(ENCODING));}// 获取返回结果if (connection.getResponseCode() == HttpStatus.SC_OK) {is = connection.getInputStream();// 封装输入流is,并指定字符集br = new BufferedReader(new InputStreamReader(is, ENCODING));// 存放数据StringBuilder sbf = new StringBuilder();String temp = null;while ((temp = br.readLine()) != null) {sbf.append(temp);sbf.append("\r\n");}return new HttpResult(connection.getResponseCode(), sbf.toString());}return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);} finally {// 释放资源release(connection, is, null, br);}}/*** Description: 释放资源*/private static void release(HttpURLConnection connection, InputStream is, OutputStream os, BufferedReader br) throws IOException {// 关闭资源if (null != br) {br.close();}if (null != os) {os.close();}if (null != is) {is.close();}// 断开与远程地址url的连接connection.disconnect();}// 将Map转换为查询字符串的辅助方法private static String convertToQueryString(Map<String, String> params) throws Exception {StringJoiner joiner = new StringJoiner("&");for (Map.Entry<String, String> entry : params.entrySet()) {joiner.add(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()));}return joiner.toString();}
}

测试类(HttpURLConnectionDemo)

java">import com.baicaizhi.utils.HttpResult;
import com.baicaizhi.utils.HttpURLConnectionUtil;
import com.google.gson.Gson;import java.util.HashMap;
import java.util.Map;/*** @author yj*/
public class HttpURLConnectionDemo {public static void main(String[] args) throws Exception {String getUrl = "http://localhost:8080/get";String getByIdUrl = "http://localhost:8080/getById";String query = "http://localhost:8080/query";String queryByUser = "http://localhost:8080/queryByUser";//不带参数getHttpResult httpResult = HttpURLConnectionUtil.doGet(getUrl, null, null);System.out.println(httpResult.toString());//带参数getMap<String, String> params = new HashMap<String, String>();params.put("id", "123456789");HttpResult httpResult1 = HttpURLConnectionUtil.doGet(getByIdUrl, new Gson().toJson(params));System.out.println(httpResult1.toString());//不带参数PostHttpResult httpResult2 = HttpURLConnectionUtil.doPost(query);System.out.println(httpResult2.toString());//带参数PostMap<String, String> user = new HashMap<String, String>();user.put("age", "22");user.put("name", "yj");user.put("sex", "男");HashMap<String, String> headers = new HashMap<>();headers.put("Content-Type", "application/json;");headers.put("Accept", "application/json");HttpResult httpResult3 = HttpURLConnectionUtil.doPost(queryByUser, headers, new Gson().toJson(user));System.out.println(httpResult3.toString());}
}

OkHttp

简介

OkHttp是一个默认有效的HTTP客户端,有效地执行HTTP可以加快您的负载并节省带宽,如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0,OkHttp支持Android 2.3及更高版本。对于Java,最低要求是1.7

调用步骤

  1. 创建OkhttpClient。
  2. mClient执行newCall将Request转化成一个Call。
  3. 最后call执行excute同步执行,enqueue异步执行。
  4. Request主要通过Request.Builder来构建。
  5. 缓存。
  6. 取消请求。

代码案例

引入依赖

<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId>
</dependency>

工具类(OkHttpUtil)

java">import okhttp3.*;
import org.apache.http.HttpStatus;import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;/*** @author yj*/
public class OkHttpUtil {private static final OkHttpClient client =new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS)       // 设置超时时间.build();private static final String ENCODING = "UTF-8";/*** 发起Get请求** @param url url* @return 响应结果*/public static HttpResult doGet(String url) throws Exception {Call call = createGetCall(url, null, null);return execute(call);}/*** 发起Get请求** @param url    url* @param params 参数* @return 响应结果*/public static HttpResult doGet(String url, Map<String, Object> params) throws Exception {Call call = createGetCall(url, null, params);return execute(call);}/*** 发起Get请求** @param url    url* @param params 参数* @return 响应结果*/public static HttpResult doGet(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {Call call = createGetCall(url, headers, params);return execute(call);}/*** 发起 Post请求, 使用form表单参数** @param url url* @return 响应结果*/public static HttpResult doPost(String url) throws Exception {Call call = createPostCall(url, null, "");return execute(call);}/*** 发起 Post请求, 使用form表单参数** @param url    url* @return 响应结果*/public static HttpResult doPost(String url, String jsonString) throws Exception {Call call = createPostCall(url, null, "");return execute(call);}/*** 发起 Post请求, 使用form表单参数** @param url    url* @return 响应结果*/public static HttpResult doPost(String url, Map<String, Object> headers, String  jsonString) throws Exception {Call call = createPostCall(url, headers, jsonString);return execute(call);}/*** Get请求, 构造 Call对象** @param url    请求url* @param params 请求参数* @return Call*/private static Call createGetCall(String url, Map<String, Object> headers, Map<String, Object> params) throws Exception {if (params != null) {url = url + "?" + convertToQueryString(params);}Request request = new Request.Builder().url(url).headers(headersToHttpHeaders(headers)).build();return client.newCall(request);}/*** Post请求, 构造 Call对象** @param url    请求url* @return Call*/private static Call createPostCall(String url, Map<String, Object> headers, String jsonString) throws Exception {Request request = new Request.Builder().post(RequestBody.create(jsonString.getBytes(ENCODING))).url(url).headers(headersToHttpHeaders(headers)).build();return client.newCall(request);}/*** 同步执行 http请求** @param call call对象* @return 响应结果*/private static HttpResult execute(Call call) throws Exception {Response execute = call.execute();if (execute.code() == HttpStatus.SC_OK) {ResponseBody body = execute.body();return new HttpResult(execute.code(), body != null ? body.toString() : "");}return new HttpResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);}// 将Map转换为查询字符串的辅助方法private static String convertToQueryString(Map<String, Object> params) throws Exception {StringJoiner joiner = new StringJoiner("&");for (Map.Entry<String, Object> entry : params.entrySet()) {joiner.add(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8.toString()) + "=" +URLEncoder.encode(String.valueOf(entry.getValue()), StandardCharsets.UTF_8.toString()));}return joiner.toString();}// 将Map转换为Headers对象的辅助方法(OkHttp没有直接提供这样的方法,因此我们需要自己实现)private static Headers headersToHttpHeaders(Map<String, Object> headers) {Headers.Builder headersBuilder = new Headers.Builder();if (headers != null) {for (Map.Entry<String, Object> entry : headers.entrySet()) {headersBuilder.add(entry.getKey(), String.valueOf(entry.getValue()));}}return headersBuilder.build();}
}

测试类

java">import com.baicaizhi.utils.HttpResult;
import com.baicaizhi.utils.OkHttpUtil;
import com.google.gson.Gson;import java.util.HashMap;
import java.util.Map;/*** @author yj*/
public class OkHttpDemo {public static void main(String[] args) throws Exception {String getUrl = "http://localhost:8080/get";String getByIdUrl = "http://localhost:8080/getById";String query = "http://localhost:8080/query";String queryByUser = "http://localhost:8080/queryByUser";//不带参数getHttpResult httpResult = OkHttpUtil.doGet(getUrl,  null);System.out.println(httpResult.toString());//带参数getMap<String, Object> params = new HashMap<String, Object>();params.put("id", "123456789");HttpResult httpResult1 = OkHttpUtil.doGet(getByIdUrl, params);System.out.println(httpResult1.toString());//不带参数PostHttpResult httpResult2 = OkHttpUtil.doPost(query);System.out.println(httpResult2.toString());//带参数PostMap<String, Object> user = new HashMap<String, Object>();user.put("age", "22");user.put("name", "yj");user.put("sex", "男");HashMap<String, Object> headers = new HashMap<>();headers.put("Content-Type", "application/json; utf-8");headers.put("Accept", "application/json");HttpResult httpResult3 = OkHttpUtil.doPost(queryByUser, headers, new Gson().toJson(user));System.out.println(httpResult3.toString());}
}

RestTemplate

简介

  • RestTemplate是Spring提供的进行远程调用客户端
  • RestTemplate提供了很多远程调用的方法,能够大大提高客户端的编写效率。
    调用RestTemplate的默认构造函数,RestTemplate对象在底层通过使用java.net包下的实现创建HTTP 请求

使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap,
ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。

代码案例

测试类(RestTemplateDemo)

java">import com.google.gson.Gson;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;import java.util.HashMap;
import java.util.Map;/*** @author yj*/
public class RestTemplateDemo {public static void main(String[] args) throws Exception {RestTemplate restTemplate = new RestTemplate();String getUrl = "http://localhost:8080/get";String getByIdUrl = "http://localhost:8080/getById";String query = "http://localhost:8080/query";String queryByUser = "http://localhost:8080/queryByUser";//不带参数getString forObject = restTemplate.getForObject(getUrl, String.class);System.out.println(forObject);//带参数getgetByIdUrl = getByIdUrl+"?id={?}";String forObject1 = restTemplate.getForObject(getByIdUrl, String.class, 123213);System.out.println(forObject1);//不带参数PostHttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> requestEntity = new HttpEntity<>(headers);String forObject2 = restTemplate.postForObject(query,requestEntity, String.class);System.out.println(forObject2);//带参数Map<String, Object> user = new HashMap<String, Object>();user.put("age", "22");user.put("name", "yj");user.put("sex", "男");HttpHeaders headers1 = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> requestEntity1 = new HttpEntity<>(new Gson().toJson(user),headers);String forObject3 = restTemplate.postForObject(queryByUser,requestEntity1, String.class);System.out.println(forObject3);}
}

http://www.ppmy.cn/news/1561605.html

相关文章

Python多分类Logistic回归详解与实践

在机器学习中&#xff0c;Logistic回归是一种基本但非常有效的分类算法。它不仅可以用于二分类问题&#xff0c;还可以扩展应用于多分类问题。本文将详细介绍如何使用Python实现一个多分类的Logistic回归模型&#xff0c;并给出详细的代码示例。 一、Logistic回归简介 Logist…

亚矩阵云手机:跨境出海直播的全方位利器

在跨境出海直播领域&#xff0c;亚矩阵云手机扮演着举足轻重的角色&#xff0c;为跨境业务中面临的诸多挑战提供了行之有效的解决方案。以下将对其作用与解决方案展开详细阐述。 一、亚矩阵云手机在跨境出海直播中的关键作用 &#xff08;一&#xff09;突破地域限制&#xff0…

英伟达 RTX 5090 显卡赋能医疗大模型:变革、挑战与展望

一、英伟达 RTX 5090 与 RTX 4090 技术参数对比 1.1 核心架构与制程工艺 在探讨英伟达 RTX 4090 与 RTX 5090 的差异时&#xff0c;核心架构与制程工艺无疑是最为关键的基础要素&#xff0c;它们从根本上决定了两款显卡的性能上限与应用潜力。 1.1.1 核心架构差异 RTX 4090…

望获实时Linux系统与大语言模型深度融合,开创实时智能无限可能!

大语言模型的崛起为智能化应用开辟了新的可能性。借助深度学习技术&#xff0c;这些模型能够理解和生成自然语言&#xff0c;处理复杂的文本和语义信息。这使得它们在诸如人机问答、内容生成和数据分析等领域展现出巨大的潜力。在实时控制领域&#xff0c;大语言模型能够显著提…

conda快速安装并配置pycharm

1、镜像下载地址 https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/2、安装完成后配置环境变量 安装记得all users 配置环境 3、配置镜像 conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ conda config --add channels https…

大疆无人机炸机,视频文件打不开怎么办

3-9 现在无人机已经非常普及和大众化&#xff0c;可以说已经是个大人玩具。 但是有时候会出意外&#xff0c;比如出现炸机的情况&#xff0c;当出现炸机的时候&#xff0c;无人机拍摄的视频有可能会出现播放不了的现象&#xff0c;比如下面这个&#xff0c;拍摄的是一个乡村的…

书籍推荐:MySQL 是怎样运行的-从根上理解 MySQL

2022-06-03 日看完这本书&#xff0c;大概花了一周的时间。整体上看得比较慢&#xff0c;书中的内容比较深&#xff0c;我看的时候需要查一下资料。 对我来说&#xff0c;在讲 MySQL 原理的书中&#xff0c;这本书可以排在第一&#xff0c;这本书侧重于 MySQL 的原理&#xff…

微信小程序获取图片使用session(上篇)

概述&#xff1a; 我们开发微信小程序&#xff0c;从后台获取图片现实的时候&#xff0c;通常采用http get的方式&#xff0c;例如以下代码 <image class"user_logo" src"{{logoUrl}}"></image>变量logoUrl为ur图片l的请求地址 但是对于很多…