HTTP GET | POST | DELETE请求

Posted huaiheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTP GET | POST | DELETE请求相关的知识,希望对你有一定的参考价值。

依赖:

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

Example:

public class MQHttpClient {
/**
* GET | POST | DELETE
*
* @param paramsMap if null and the request is Get,otherwise dependent on requestMethodEnum
* @param paramsMap if the request is post,and you can put the params in the map otherwise to null
* @param cookie if you need cookie to veriy,you can use it, otherwise to null
* @return responseJsonString
*/
public static String sendRequestURL(String url, HashMap<String, Object> paramsMap, RequestMethodEnum requestMethodEnum, String cookie) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, com.alibaba.fastjson.JSON.toJSONString(paramsMap, true));
Request.Builder request = new Request.Builder();
Response response;
try {
OkHttpClient client = new OkHttpClient.Builder().build();
// GET
if (paramsMap == null) {
if (cookie != null) {
response = client.newCall(request.url(url).addHeader("cookie", cookie).get().build()).execute();
} else {
response = client.newCall(request.url(url).get().build()).execute();
}
} else { // POST || DELETE
if (requestMethodEnum.getValue().equals(RequestMethodEnum.POST.getValue())) {
if (cookie != null) {
response = client.newCall((request.url(url).post(body)).addHeader("cookie", cookie).build()).execute();
} else {
response = client.newCall((request.url(url).post(body)).build()).execute();
}
} else {
if (cookie != null) {
response = client.newCall((request.url(url).post(body)).addHeader("cookie", cookie).build()).execute();
} else {
response = client.newCall((request.url(url).post(body)).build()).execute();
}
}
}
String responseBody = response.body().string();
return responseBody;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

以上是关于HTTP GET | POST | DELETE请求的主要内容,如果未能解决你的问题,请参考以下文章

Http四种请求方式:post ,get ,put,delete

在Web Api中实现Http方法(Get,Put,Post,Delete)

解析HTTP协议六种请求方法,get,head,put,delete,post有啥区别

post、get、put、patch、Delete的区别

HTTP GET | POST | DELETE请求

httpclient 封装 http(get put post delete)请求