文章目录
- 前言
- 通用接口类(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)
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)
@Data
@ToString
@Accessors(chain = true)
public class UserEntity {String name;int age;String sex;
}
通用响应类(HttpClientResult)
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方法)
HttpClient
HttpClient 的主要类
- java.net.http.HttpClient
HttpClient是用于发送HTTP请求和处理HTTP响应的主要类。它提供了一种简单且一致的方式来执行HTTP操作,包括同步和异步的请求发送、连接池管理、请求和响应的拦截器等功能。
- java.net.http.HttpRequest
HttpRequest是用于表示HTTP请求的类。通过HttpRequest对象,您可以设置请求的URL、请求方法、请求头、请求体等信息,并构建一个完整的HTTP请求对象,用于发送给服务器。
- java.net.http.HttpResponse
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)
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();}}
}
测试类
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完成更安全的请求操作。
调用步骤
- 创建一个URL对象:URL url=new URL(“接口地址”)
- 调用URL对象的openConnection()来获取HttpURLConnection对象实例;
HttpURLConnection connection= (HttpURLConnection) url.openConnection(); - 设置HTTP请求使用的方法:GET、POST或其他请求;
connection.setRequestMethod(“GET”); - 设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头;
connection.setConnectTimeout(6*1000);
connection.setReadTimeout(6 * 1000); - 调用getInputStream()方法获得服务器返回的输入流,然后输入流进行读取了;
InputStream in = connection.getInputStream(); - 最后调用disconnect()方法将HTTP连接关掉;
connection.disconnect();
代码案例
导入依赖
本工具类中使用到了Gson,所以需要导入一下依赖
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId>
</dependency>
工具类(HttpURLConnectionUtil)
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)
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
调用步骤
- 创建OkhttpClient。
- mClient执行newCall将Request转化成一个Call。
- 最后call执行excute同步执行,enqueue异步执行。
- Request主要通过Request.Builder来构建。
- 缓存。
- 取消请求。
代码案例
引入依赖
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId>
</dependency>
工具类(OkHttpUtil)
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();}
}
测试类
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)
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);}
}