代码拉取完成,页面将自动刷新
package com.nowcoder.enterprise.javademo.utils;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* 请求牛客API工具类
*
* @author guokaijun
* @date 2021/7/31
*/
public class NowcoderApiRequestUtils {
/**
* HTTP调用牛客API并返回字符串,在调用之前根据请求方法设置了通用的请求头和请求参数,并将方法传入的参数置入HTTP请求中。
*
* @param path 请求路径,形如"/users/self"的字符串
* @param params 请求参数,需传递除api_key参数之外的每个接口独有的参数。一个key能对应多个值,值不能为null。
* 如果接口不需要其他参数,需要传递空Map,不能传null。
* @param methodName http方法名称。取值范围为 GET、POST、PUT、DELETE 中的一个
* @return 牛客接口json返回的字符串表示
*/
public static String request(
String path, MultiValuedMap<String, Object> params, String methodName) {
if (HttpGet.METHOD_NAME.equals(methodName)) {
return getRequest(path, params);
}
HttpEntityEnclosingRequestBase uriRequest = getMethod(methodName);
uriRequest.setURI(URI.create(ConfigUtils.getApiBaseUrl() + path));
List<NameValuePair> pairList = new ArrayList<>();
pairList.add(new BasicNameValuePair("api_key", ConfigUtils.getApiKey()));
params
.entries()
.forEach(
(entry) -> {
String key = entry.getKey();
Object val = entry.getValue();
if (key == null || val == null) return;
pairList.add(new BasicNameValuePair(key, val.toString()));
});
uriRequest.setEntity(new UrlEncodedFormEntity(pairList, StandardCharsets.UTF_8));
uriRequest.addHeader("Authorization", ConfigUtils.getAuthorization());
return sendRequest(uriRequest);
}
private static HttpEntityEnclosingRequestBase getMethod(String methodName){
HttpEntityEnclosingRequestBase uriRequest;
if (HttpPost.METHOD_NAME.equals(methodName)) {
uriRequest = new HttpPost();
} else if (HttpPut.METHOD_NAME.equals(methodName)) {
uriRequest = new HttpPut();
} else if (HttpDelete.METHOD_NAME.equals(methodName)) {
uriRequest = new NowcoderHttpDelete();
} else {
throw new IllegalArgumentException("Bad methodName.");
}
return uriRequest;
}
public static String jsonRequest(String path, Object param, String methodName){
HttpEntityEnclosingRequestBase uriRequest = getMethod(methodName);
uriRequest.setURI(URI.create(ConfigUtils.getApiBaseUrl() + path + "?api_key=" + ConfigUtils.getApiKey()));
uriRequest.setEntity(new StringEntity(JSON.toJSONString(param), Charset.defaultCharset()));
uriRequest.addHeader("Authorization", ConfigUtils.getAuthorization());
uriRequest.addHeader("Content-Type", "application/json");
return sendRequest(uriRequest);
}
// 执行GET请求
private static String getRequest(String path, MultiValuedMap<String, Object> params) {
List<String> pairs = new ArrayList<>();
pairs.add("api_key=" + ConfigUtils.getApiKey());
params
.entries()
.forEach(
(entry) -> {
String key = entry.getKey();
Object val = entry.getValue();
if (key == null || val == null) return;
pairs.add(key + "=" + val);
});
String queryParams = StringUtils.join(pairs, "&");
HttpGet get = new HttpGet(ConfigUtils.getApiBaseUrl() + path + "?" + queryParams);
get.addHeader("Authorization", ConfigUtils.getAuthorization());
return sendRequest(get);
}
// 发送请求并打印CURL
private static String sendRequest(HttpRequestBase requestBase) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String responseString = null;
try {
CloseableHttpResponse response = httpClient.execute(requestBase);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
String curlStr = toCurlStr(requestBase);
System.out.println(curlStr);
return responseString;
}
// 将一次HTTP请求转换成CURL
private static String toCurlStr(HttpRequestBase requestBase) {
String httpMethod = requestBase.getMethod();
String uri = requestBase.getURI().toString();
List<String> headers = new ArrayList<>();
for (Header header : requestBase.getAllHeaders()) {
headers.add(header.getName() + ": " + header.getValue());
}
String headersStr = "";
if (CollectionUtils.isNotEmpty(headers)) {
for (String header : headers) {
headersStr += "\\\n --header '" + header + "' ";
}
}
String dataRawStr = "";
if (requestBase instanceof HttpEntityEnclosingRequestBase) {
HttpEntity entity = ((HttpEntityEnclosingRequestBase) requestBase).getEntity();
try {
dataRawStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
if (StringUtils.isNotEmpty(dataRawStr)) {
dataRawStr = String.format("\\\n --data-raw '%s'", dataRawStr);
}
String template = "curl --location --request %s '%s' %s %s";
return String.format(template, httpMethod, uri, headersStr, dataRawStr);
}
// 将一次HTTP请求转换成CURL
private static String toJsonCurlStr(HttpRequestBase requestBase) {
String httpMethod = requestBase.getMethod();
String uri = requestBase.getURI().toString();
List<String> headers = new ArrayList<>();
for (Header header : requestBase.getAllHeaders()) {
headers.add(header.getName() + ": " + header.getValue());
}
String headersStr = "";
if (CollectionUtils.isNotEmpty(headers)) {
for (String header : headers) {
headersStr += "\\\n --header '" + header + "' ";
}
}
String dataRawStr = "";
if (requestBase instanceof HttpEntityEnclosingRequestBase) {
HttpEntity entity = ((HttpEntityEnclosingRequestBase) requestBase).getEntity();
try {
dataRawStr = EntityUtils.toString(entity, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
}
if (StringUtils.isNotEmpty(dataRawStr)) {
dataRawStr = String.format("\\\n --data-raw '%s'", dataRawStr);
}
String template = "curl --location --request %s '%s' %s %s";
return String.format(template, httpMethod, uri, headersStr, dataRawStr);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。