java在http请求中使用CORS
今天,我有以下问题。我想向rest api发出http请求,但我只收到一个405错误。我搜索了一下,发现api使用cors。 那么我如何使用cors发出http请求呢
这是我的http客户端:
package community.opencode.minetools4j.util.http;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NonNull;
import org.apache.commons.io.IOUtils;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* This is an utility class.
* It simplify making HTTP requests
*/
public class HttpRequest {
/**
* Performs a new HTTP request
*
* @param requestBuilder See {@link RequestBuilder}
* @return See {@link RequestResponse}
* @throws IOException Will be thrown if the request can't be executed
*/
public static RequestResponse performRequest(RequestBuilder requestBuilder) throws IOException {
URL newUrl = new URL(requestBuilder.getPath());
HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();
connection.setRequestMethod(requestBuilder.getMethod().getType());
requestBuilder.getHeaders().forEach(connection::setRequestProperty);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setDoOutput(true);
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(getParametersString(requestBuilder.getParams()));
int status = connection.getResponseCode();
String result = IOUtils.toString(connection.getInputStream(), "UTF-8");
String contentType = connection.getHeaderField("Content-Type");
connection.getInputStream().close();
connection.disconnect();
return new RequestResponse(status, result, contentType);
}
/**
* Makes from a map a valid HTTP string
* Example: "myField=Hey!&myPassword=abc"
*
* @param params The parameters
* @return The formed String
* @throws UnsupportedEncodingException Should never be thrown
*/
private static String getParametersString(Map<String, String> params) throws UnsupportedEncodingException {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
builder.append("&");
}
String result = builder.toString();
return result.length() > 0 ? result.substring(0, result.length() - 1) : result;
}
/**
* A simple builder class for {@link #performRequest(RequestBuilder)}
*/
@Data
public static class RequestBuilder {
private final String path;
private final HttpRequestMethod method;
private final Map<String, String> params = new HashMap<>();
private final Map<String, String> headers = new HashMap<>();
public RequestBuilder addParam(@NonNull String name, @NonNull String value) {
this.params.put(name, value);
return this;
}
public RequestBuilder addHeader(@NonNull String name, @NonNull String value) {
this.headers.put(name, value);
return this;
}
}
/**
* A simplified http response.
* Including status, message and the returned content type
*/
@Data
@AllArgsConstructor
public static class RequestResponse {
private int status;
private String resultMessage;
private String contentType;
}
}
package community.opencode.minetools4j.util.http;
import lombok.Getter;
/**
* Simple enum for {@link HttpRequest}.
* It's a better way than just write manually the method name
*/
public enum HttpRequestMethod {
POST("POST"),
GET("GET"),
PUT("PUT"),
HEAD("HEAD"),
OPTIONS("OPTIONS"),
DELETE("DELETE"),
TRACE("TRACE");
@Getter
private String type;
HttpRequestMethod(String type) {
this.type = type;
}
}
下面是我发出http请求的方法:
HttpRequest.RequestResponse requestResponse = HttpRequest.performRequest(new HttpRequest.RequestBuilder(API_URI + "/ping/" + host + "/" + port, HttpRequestMethod.GET));
谢谢大家的关注
真诚地, 斯凯莱格
对不起,我英语不好。我希望你能理解我;)
# 1 楼答案
如果您遇到此类错误:
您必须创建一个servlet过滤器,并在doFilter方法上添加下面的代码
# 2 楼答案
什么是HTTP代码405
状态405表示您发送的请求不允许您使用的方法
Source
如何修复
您需要检查API文档,看看是否有以下错误:
简化代码
使用unirest可以简化您的请求代码,并覆盖边缘情况