码迷,mamicode.com
首页 > Web开发 > 详细

HTTP GET | POST | DELETE请求

时间:2020-05-02 12:14:06      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:charset   ade   hash   div   deb   请求   @param   use   catch   

依赖:

<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请求

标签:charset   ade   hash   div   deb   请求   @param   use   catch   

原文地址:https://www.cnblogs.com/huaiheng/p/12817240.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!