【问题标题】:HTTP requests with basic authentication具有基本身份验证的 HTTP 请求
【发布时间】:2011-01-07 15:57:08
【问题描述】:

我必须从 http 服务器下载和解析 XML 文件使用 HTTP Basic 身份验证。现在我正在这样做:

URL url = new URL("http://SERVER.WITHOUT.AUTHENTICATION/some.xml");
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(new InputSource(url.openStream()));
     doc.getDocumentElement().normalize();

但是这样我就无法通过 http 身份验证从服务器获取 xml(或者我只是不知道)文档。

如果您能告诉我实现目标的最佳和最简单的方法,我将不胜感激。

【问题讨论】:

    标签: java android


    【解决方案1】:

    您可以使用Authenticator。例如:

    Authenticator.setDefault(new Authenticator() {
     @Override
            protected PasswordAuthentication getPasswordAuthentication() {
             return new PasswordAuthentication(
       "user", "password".toCharArray());
            }
    });
    

    这将设置默认的Authenticator,并将在所有请求中使用。显然,当您不需要所有请求的凭据或许多不同的凭据(可能在不同的线程上)时,设置会更复杂。

    或者,您可以使用DefaultHttpClient,其中带有基本 HTTP 身份验证的 GET 请求类似于:

    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://foo.com/bar");
    httpGet.addHeader(BasicScheme.authenticate(
     new UsernamePasswordCredentials("user", "password"),
     "UTF-8", false));
    
    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity responseEntity = httpResponse.getEntity();
    
    // read the stream returned by responseEntity.getContent()
    

    我建议使用后者,因为它可以让您对您的请求进行更多控制(例如方法、标头、超时等)。

    【讨论】:

      【解决方案2】:
      public String reloadTomcatWebApplication(String user, String pwd, String urlWithParameters, boolean returnResponse) {
          URL url = null;
          try {
              url = new URL(urlWithParameters);
          } catch (MalformedURLException e) {
              System.out.println("MalformedUrlException: " + e.getMessage());
              e.printStackTrace();
              return "-1";
          }
      
          URLConnection uc = null;
          try {
              uc = url.openConnection();
          } catch (IOException e) {
              System.out.println("IOException: " + e.getMessage());
              e.printStackTrace();
              return "-12";
          }
      
      
          String userpass = user + ":" + pwd;
          String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
      
          uc.setRequestProperty("Authorization", basicAuth);
          InputStream is = null;
          try {
              is = uc.getInputStream();
          } catch (IOException e) {
              System.out.println("IOException: " + e.getMessage());
              e.printStackTrace();
              return "-13";
          }
          if (returnResponse) {
              BufferedReader buffReader = new BufferedReader(new InputStreamReader(is));
              StringBuffer response = new StringBuffer();
      
              String line = null;
              try {
                  line = buffReader.readLine();
              } catch (IOException e) {
                  e.printStackTrace();
                  return "-1";
              }
              while (line != null) {
                  response.append(line);
                  response.append('\n');
                  try {
                      line = buffReader.readLine();
                  } catch (IOException e) {
                      System.out.println(" IOException: " + e.getMessage());
                      e.printStackTrace();
                      return "-14";
                  }
              }
              try {
                  buffReader.close();
              } catch (IOException e) {
                  e.printStackTrace();
                  return "-15";
              }
              System.out.println("Response: " + response.toString());
              return response.toString();
          }
          return "0";
      }
      

      【讨论】:

        【解决方案3】:

        使用 HttpClient。使用 HTTP AUTH 执行下载的文档是 here。获取字符串结果的文档是here。然后,解析您的字符串(最好使用 SAX,而不是 DOM)。

        【讨论】:

          【解决方案4】:
          • DefaultHttpClient 已弃用
          • addHeader 必须有 2 个参数

          使用 HttpClient 4.5.2 更新代码块

          HttpClient httpClient = HttpClientBuilder.create().build();
          HttpGet httpGet = new HttpGet("https://test.com/abc.xyz");
          httpGet.addHeader("Authorization", BasicScheme.authenticate(new UsernamePasswordCredentials("login", "password"), "UTF-8"));
          
          HttpResponse httpResponse = httpClient.execute(httpGet);
          HttpEntity responseEntity = httpResponse.getEntity();
          

          【讨论】:

            【解决方案5】:

            正如 Gabe Rogan 所说,“从 BasicScheme 进行身份验证的方法已被弃用”。

            另一种方法,

            HttpRequestBase hrb = new HttpGet(req.getUrl()); // should be your URL    
            UsernamePasswordCredentials Credential= new UsernamePasswordCredentials("id", "password");
            Header header = new BasicScheme(StandardCharsets.UTF_8).authenticate(Credential, hrb, null);
            hrb.addHeader(header);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2019-09-11
              • 1970-01-01
              • 2016-09-29
              • 2017-07-23
              • 1970-01-01
              • 2019-05-09
              相关资源
              最近更新 更多