代码之家  ›  专栏  ›  技术社区  ›  Edward Dale

使用httpclient 4.x验证单个请求

  •  3
  • Edward Dale  · 技术社区  · 14 年前

    我有一个 HttpClient 由多个线程共享的实例。我想用它发出一个经过身份验证的请求。因为只应对单个请求进行身份验证,所以我不想修改 HTTP客户端 实例,如 documentation . 这是我做出来的,但没有用。据我所知,它看起来不像 CredentialsProvider 正在被使用。有什么小窍门吗?

    HttpContext context = null;
    if(feedSpec.isAuthenticated()) {
      context = new BasicHttpContext();
      CredentialsProvider credsProvider = new BasicCredentialsProvider();
      credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(feedSpec.getHttpUsername(), feedSpec.getHttpPassword()));
      context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
      context.setAttribute(ClientPNames.HANDLE_AUTHENTICATION, true);
    }
    HttpGet httpGet = new HttpGet(feedSpec.getUri());
    HttpResponse httpResponse = httpClient.execute(httpGet, context);
    
    1 回复  |  直到 12 年前
        1
  •  3
  •   Edward Dale    14 年前

    原来我连接的服务器只提供ntlm身份验证。我使用指南实现了ntlm身份验证 here . 我修改了问题中列出的代码,使其看起来是这样,并且它起作用:

    HttpContext context = null;
    if(feedSpec.isAuthenticated()) {
        context = new BasicHttpContext();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new NTCredentials(feedSpec.getHttpUsername(), feedSpec.getHttpPassword(), "", ""));
        context.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);
    }
    HttpGet httpGet = new HttpGet(feedSpec.getUri());
    HttpResponse httpResponse = httpClient.execute(httpGet, context);