如何处理 java 中的 302 重定向

How to handle 302 redirection in java

我有一个 url,我正在从中获取令牌。那部分工作正常。然后这个令牌在另一个 url 中被用来获取价值。 但是在这样做时我收到了 302 错误。因此,我尝试从响应 header 中获取位置参数并在 url 中使用它。但是我收到以下错误

org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:187)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at com.citi.clg.originations.strategic.service.CertDashboardServiceImpl.getService(CertDashboardServiceImpl.java:800)
    at com.citi.clg.originations.strategic.dwr.CertDashboardAJAXLookup.getService(CertDashboardAJAXLookup.java:114)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.directwebremoting.impl.CreatorModule.doFilter(CreatorModule.java:172)
    at org.directwebremoting.impl.CreatorModule.executeMethod(CreatorModule.java:184)
    at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:353)
    at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:306)
    at org.directwebremoting.dwrp.BaseCallHandler.handle(BaseCallHandler.java:110)
    at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:211)
    at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:185)
    at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:144)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:138)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.http.ProtocolException: Target host is not specified
    at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    ... 43 more

下面是我的代码

String id=jobj1.get("ID").toString();
          try {
                HttpPost httpPost;
          httpPost = new HttpPost(
                    "https://example.com");

        //httpPost.setEntity(new StringEntity(data));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        CloseableHttpResponse response = client.execute(httpPost);
        System.out.println(response.getEntity().getContent());
        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println(response.getHeaders("Location").toString());
        String tempUrl=response.getHeaders("Location")[0].getValue().replaceAll(" ", "%20");
        System.out.println(response.getHeaders("Location")[0].getValue().replaceAll(" ","%20"));
        System.out.println(tempUrl.replace("|","%7c"));
        if(response.getStatusLine().getStatusCode()==302)
        {
            System.out.println(response.getHeaders("Location")[0].getValue().replaceAll(" ", "%20").replace("|", "%7c"));
            httpPost=new HttpPost(URLEncoder.encode(response.getHeaders("Location")[0].getValue(),"UTF-8"));
            //httpPost=new HttpPost(response.getHeaders("Location")[0].getValue().replaceAll(" ", "%20").replace("|", "%7c"));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
             response = client.execute(httpPost);
        }
        if (response.getStatusLine().getStatusCode() == 200 ) {
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            String output;
            while ((output = br.readLine()) != null) {
                responseData = responseData + output;
            }
        } else {
            responseData = "{\"status\": \"ERROR\"}";
        }

    } catch (Exception e) {
        e.printStackTrace();
        responseData = "{\"status\": \"ERROR\"}";
    } finally {
        try {
            client.close();
        } catch (IOException e) {
        }
    }

这是我的重定向 url

位置:/enlight.server/login.jsp?goto=/enlight.server/html/scripts/api/assets.jsp?all=true&globalCrit=Host where name:sdcgcgtiblb20pv | Until>1d AND Until<31d &action=table&envId=92738683& EvolvenSessionKey=377d58e55aa4b81eaeb9028226b7a64565c57fc9&Json=true

的证书

我注意到你使用 apache-httpclient 4.x。

您可以覆盖默认行为以遵循重定向:

对于 HttpClient 4.3 及更高版本

HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpResponse response = instance.execute(new HttpPost("http://example.com"));

对于 HttpClient 4.2

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
HttpResponse response = client.execute(new HttpPost("http://example.com"));

HttpClient 4.2 之前

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
    private String[] REDIRECT_METHODS = new String[] { 
        HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME 
    };

    @Override
    protected boolean isRedirectable(String method) {
        for (String m : REDIRECT_METHODS) {
            if (m.equalsIgnoreCase(method)) {
                return true;
            }
        }
        return false;
    }
});

HttpResponse response = client.execute(new HttpPost("http://example.com"));

我一直在获取令牌并关闭会话并重新打开会话,这导致令牌无效和重定向