由于公司做电商很多平台都要求自己写http请求,因此写一下自己的感悟,希望可以帮助到有需要的人,token为授权信息,每个平台要求不同,map种存放请求参数,key为参数名,value为参数值
public static String sendPatch(String url, Map params, String token) {
String result = "";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPatch httpPatch = new HttpPatch(url);
httpPatch.setHeader("Content-type", "application/json");
httpPatch.setHeader("Charset", HTTP.UTF_8);
httpPatch.setHeader("Accept", "application/json");
httpPatch.setHeader("Accept-Charset", HTTP.UTF_8);
httpPatch.setHeader("Authorization", "Bearer " + token);
try {
StringEntity data = new StringEntity(JSONObject.fromObject(params).toString(), HTTP.UTF_8);
httpPatch.setEntity(data);
HttpResponse response = httpClient.execute(httpPatch);
HttpEntity entity = response.getEntity();
int code = response.getStatusLine().getStatusCode();
result = EntityUtils.toString(entity);
} catch (Exception e) {
result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
}
return result;
}
public static String sendDelete(String url, Map param, String token) {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient(url);
HttpDelete httpDelete = new HttpDelete(url);
setRequestConfig(httpDelete);
httpDelete.addHeader("User-Agent", DefaultUserAgent);
//param.forEach((k, v) -> httpDelete.addHeader(k, com.alibaba.fastjson.JSONObject.toJSONString(v)));
httpDelete.setHeader("Authorization", "Bearer " + token);
HttpResponse httpResponse = httpClient.execute(httpDelete, HttpClientContext.create());
HttpEntity resEntity = httpResponse.getEntity();
if (null == resEntity) {
result = "{\"status\":\"0\",\"error\":\"success\"}";
} else {
result = EntityUtils.toString(resEntity);
}
} catch (Exception e) {
result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
}
return result;
}
public static String sendPut(String urlPath, Map param, String token) {
String result = null;
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(urlPath);
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setRequestProperty("Authorization", "Bearer " + token);
httpurlconnection.setRequestMethod("PUT");
httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpurlconnection.getOutputStream().write(com.alibaba.fastjson.JSONObject.toJSONString(param).getBytes("UTF-8"));
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
int code = httpurlconnection.getResponseCode();
if (code == 200) {
DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
int len = in.available();
byte[] by = new byte[len];
in.readFully(by);
result = new String(by, Charset.forName("UTF-8"));
in.close();
} else if (code == 204) {
result = "{\"code\":0,\"message\":\"success\"}";
} else if (code == 202) {
result = "{\"code\":0,\"message\":\"success\"}";
} else {
DataInputStream in = new DataInputStream(httpurlconnection.getErrorStream());
int len = in.available();
byte[] by = new byte[len];
in.readFully(by);
result = new String(by, Charset.forName("UTF-8"));
in.close();
}
} catch (Exception e) {
result = "{\"status\":\"1\",\"error\":\"" + e.getMessage() + "\"}";
} finally {
url = null;
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
}
return result;
}
public static String sendGet(String url, Map params, String token) {
String result = "";
int err = 0;
while (true) {
params.put("access_token", token);
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
List parameters = new ArrayList();
for (Map.Entry entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
HttpGet httpGet = new HttpGet(url);
StringBuilder dataparm = new StringBuilder();
params.forEach((k, v) -> dataparm.append("&" + k + "=" + v));
String urlparm = "";
String string = dataparm.toString();
if (!"".equals(string)) {
urlparm = dataparm.toString().substring(1);
}
HttpGet httpget = new HttpGet(url + "?" + urlparm);
setRequestConfig(httpget);
httpget.addHeader("User-Agent", DefaultUserAgent);
httpget.addHeader("Content-Type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpget, HttpClientContext.create());
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
return result;
} catch (IOException e) {
result = "{\"status\":\"1\",\"errors\":\"" + e.getMessage() + "\"}";
if (err++ > 2) {
break;
}
try {
Thread.sleep((err + 2) * 1000);
} catch (InterruptedException e1) {
result = "{\"status\":\"1\",\"errors\":\"" + e1.getMessage() + "\"}";
}
}
}
return result;
}
public static String sendPost(String url, Map params, String token) {
String result = "";
int err = 0;
while (true) {
params.put("access_token", token);
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new ByteArrayEntity(com.alibaba.fastjson.JSONObject.toJSONString(params).getBytes("UTF-8")));
HttpResponse httpResponse = client.execute(httpPost, HttpClientContext.create());
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
return result;
} catch (IOException e) {
result = "{\"status\":\"1\",\"errors\":\"" + e.getMessage() + "\"}";
if (err++ > 2) {
break;
}
try {
Thread.sleep((err + 2) * 1000);
} catch (InterruptedException e1) {
result = "{\"status\":\"1\",\"errors\":\"" + e1.getMessage() + "\"}";
}
}
}
return result;
}