首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HTTP/1.1 401未经授权[服务器: Apache-Coyote/1.1,缓存控制:私有

HTTP/1.1 401未经授权[服务器: Apache-Coyote/1.1,缓存控制:私有
EN

Stack Overflow用户
提问于 2017-06-14 00:39:12
回答 0查看 860关注 0票数 0

我想要点击网址,并读取内容从网址使用java代码成功。我已经尝试了许多其他方法来实现这一点,但不是success.Please请看下面摘自here的代码

代码语言:javascript
复制
import org.apache.http.*;
import org.apache.http.auth.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Simple class to launch a jenkins build on run@Cloud platform, should also work on every jenkins instance (not tested)
 *
 */
public class TestPreemptive {
    public static void main(String[] args) {

        // Credentials
        String username = "username";
        String password = "password";

        // Jenkins url
        String jenkinsUrl = "https://xyz.abc.com";

        // Build name
        String jobName = "myReportname";

        // Build token
        String buildToken = "successfulBuild";

        // Create your httpclient
        DefaultHttpClient client = new DefaultHttpClient();

        // Then provide the right credentials
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        // Generate BASIC scheme object and stick it to the execution context
        BasicScheme basicAuth = new BasicScheme();
        BasicHttpContext context = new BasicHttpContext();
        context.setAttribute("preemptive-auth", basicAuth);

        // Add as the first (because of the zero) request interceptor
        // It will first intercept the request and preemptively initialize the authentication scheme if there is not
        client.addRequestInterceptor(new PreemptiveAuth(), 0);

        // You get request that will start the build
        String getUrl = jenkinsUrl + "/job/" + jobName + "/build?token=" + buildToken;
        HttpGet get = new HttpGet(getUrl);

        try {
            // Execute your request with the given context
            HttpResponse response = client.execute(get, context);
            System.out.print("response : " + response);
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    static class PreemptiveAuth implements HttpRequestInterceptor {

        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            // Get the AuthState
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

            // If no auth scheme available yet, try to initialize it preemptively
            if (authState.getAuthScheme() == null) {
                AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                if (authScheme != null) {
                    Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost
                            .getPort()));
                    if (creds == null) {
                        throw new HttpException("No credentials for preemptive authentication");
                    }
                    authState.setAuthScheme(authScheme);
                    authState.setCredentials(creds);
                }
            }

        }

    }
}

以下是例外情况:

代码语言:javascript
复制
response : HTTP/1.1 401 Unauthorized [Server: Apache-Coyote/1.1, Cache-Control: private, Expires: Wed, 31 Dec 1969 19:00:00 EST, X-Content-Type-Options: nosniff, WWW-Authenticate: Basic realm="Jenkins", Content-Type: text/html;charset=utf-8, Content-Language: en, Content-Length: 1072, Date: Tue, 13 Jun 2017 16:30:53 GMT] org.apache.http.conn.BasicManagedEntity@2aa5fe93

我可以通过浏览器访问该网址,但无法从java code.Any获得连接建议,以解决上述错误将是有帮助的。我尝试使用Authenticator API设置凭据,但仍然面临相同的问题。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44527166

复制
相关文章

相似问题

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