首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在http请求中使用CORS

在http请求中使用CORS
EN

Stack Overflow用户
提问于 2017-09-24 15:01:02
回答 2查看 3.4K关注 0票数 0

今天,我有以下问题。我想向rest发出一个http请求,但是我只得到一个405错误。我搜索了一下,发现api使用cors。那么我怎样才能用cors发出http请求呢?

这是我的http客户端:

代码语言:javascript
复制
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请求的方法:

代码语言:javascript
复制
HttpRequest.RequestResponse requestResponse = HttpRequest.performRequest(new HttpRequest.RequestBuilder(API_URI + "/ping/" + host + "/" + port, HttpRequestMethod.GET));

感谢您的关注。

真诚的,天星

对不起我的英语不好。我希望你能理解我;)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-24 17:45:16

什么是HTTP代码405

状态405意味着在发送的请求中不允许使用您正在使用的方法。

来源

如何修复

您需要检查API文档,以确定是否有以下错误:

  • 缺少Auth报头
  • 缺失内容
  • 错误URL
  • 错误方法

简化代码

使用unirest可以简化您的请求代码,并覆盖边缘情况。

票数 0
EN

Stack Overflow用户

发布于 2017-09-24 15:48:54

如果您收到这种类型的错误:

对飞行前请求的响应不会通过访问控制检查:请求的资源上没有“访问-控制-允许-原产地”标题。因此,“http://localhost:4200”源是不允许访问的。响应具有HTTP状态代码405。

您必须创建一个servlet过滤器,并在doFilter方法上添加下面的代码。

代码语言:javascript
复制
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;

    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,HEAD");
    resp.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    resp.addHeader("Accept-Encoding", "multipart/form-data");

    if (request.getMethod().equals("OPTIONS")) {
        resp.setStatus(200);
        return;
    }
    chain.doFilter(request, servletResponse);
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46391439

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档