【问题标题】:Adding header for HttpURLConnection为 HttpURLConnection 添加标头
【发布时间】:2017-09-02 16:14:16
【问题描述】:

我正在尝试使用HttpUrlConnection 为我的请求添加标头,但setRequestProperty() 方法似乎不起作用。服务器端没有收到任何带有我的标头的请求。

HttpURLConnection hc;
    try {
        String authorization = "";
        URL address = new URL(url);
        hc = (HttpURLConnection) address.openConnection();


        hc.setDoOutput(true);
        hc.setDoInput(true);
        hc.setUseCaches(false);

        if (username != null && password != null) {
            authorization = username + ":" + password;
        }

        if (authorization != null) {
            byte[] encodedBytes;
            encodedBytes = Base64.encode(authorization.getBytes(), 0);
            authorization = "Basic " + encodedBytes;
            hc.setRequestProperty("Authorization", authorization);
        }

【问题讨论】:

  • 为我工作,你如何判断标头已发送但未收到?
  • 很抱歉,这听起来很愚蠢,但是您在哪里调用 URLConnection 上的 connect()
  • 我不确定这是否有效果,但您可以尝试添加 connection.setRequestMethod("GET");(或 POST 或任何您想要的)?
  • 您将authorization 初始化为空字符串。如果usernamepassword 为空,那么authorization 将是空字符串,而不是空字符串。因此,在我看来,最终的 if 将被执行,但 "Authorization" 属性将设置为空。

标签: java http


【解决方案1】:

我过去使用过以下代码,它在 TomCat 中启用了基本身份验证:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

你可以试试上面的代码。上面的代码是POST的,你可以修改它为GET

【讨论】:

  • Android 开发者的一点补充(API >= 8 a.k.a 2.2):android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT); Base64.DEFAULT 告诉使用 RFC2045 进行 base64 编码。
  • @Denis,你能告诉我为什么要使用标题。我必须从 android 验证一些凭据我在 xammp 上使用 php。我该怎么做。因为我不知道如何用 headers 编写 php 代码
  • 在您的示例中变量postData 来自哪里?
  • 为什么大家都叫他们Headers的时候叫他们“RequestProperty”??
  • Java8 版本的一个补充:Base64 类有点改变。解码应该使用:String basicAuth = "Basic " + java.util.Base64.getEncoder().encodeToString(userCredentials.getBytes());
【解决方案2】:

只是因为我在上面的答案中没有看到这一点信息,最初发布的代码 sn-p 无法正常工作的原因是因为 encodedBytes 变量是 byte[] 而不是 @987654323 @ 价值。如果您将byte[] 传递给new String(),如下所示,代码 sn-p 可以完美运行。

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);

【讨论】:

    【解决方案3】:

    如果您使用的是 Java 8,请使用以下代码。

    URLConnection connection = url.openConnection();
    HttpURLConnection httpConn = (HttpURLConnection) connection;
    
    String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
    httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);
    

    【讨论】:

      【解决方案4】:

      最后这对我有用

      private String buildBasicAuthorizationString(String username, String password) {
      
          String credentials = username + ":" + password;
          return "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.NO_WRAP));
      }
      

      【讨论】:

      • @d3dave。字符串是从字节数组创建的,并与“基本”连接。 OP 代码中的问题是他将“Basic”与 byte[] 连接起来并将其作为标头发送。
      【解决方案5】:

      你的代码没问题。你也可以这样用同样的东西。

      public static String getResponseFromJsonURL(String url) {
          String jsonResponse = null;
          if (CommonUtility.isNotEmpty(url)) {
              try {
                  /************** For getting response from HTTP URL start ***************/
                  URL object = new URL(url);
      
                  HttpURLConnection connection = (HttpURLConnection) object
                          .openConnection();
                  // int timeOut = connection.getReadTimeout();
                  connection.setReadTimeout(60 * 1000);
                  connection.setConnectTimeout(60 * 1000);
                  String authorization="xyz:xyz$123";
                  String encodedAuth="Basic "+Base64.encode(authorization.getBytes());
                  connection.setRequestProperty("Authorization", encodedAuth);
                  int responseCode = connection.getResponseCode();
                  //String responseMsg = connection.getResponseMessage();
      
                  if (responseCode == 200) {
                      InputStream inputStr = connection.getInputStream();
                      String encoding = connection.getContentEncoding() == null ? "UTF-8"
                              : connection.getContentEncoding();
                      jsonResponse = IOUtils.toString(inputStr, encoding);
                      /************** For getting response from HTTP URL end ***************/
      
                  }
              } catch (Exception e) {
                  e.printStackTrace();
      
              }
          }
          return jsonResponse;
      }
      

      如果授权成功则返回响应码 200

      【讨论】:

        【解决方案6】:

        使用RestAssurd,您还可以执行以下操作:

        String path = baseApiUrl; //This is the base url of the API tested
            URL url = new URL(path);
            given(). //Rest Assured syntax 
                    contentType("application/json"). //API content type
                    given().header("headerName", "headerValue"). //Some API contains headers to run with the API 
                    when().
                    get(url).
                    then().
                    statusCode(200); //Assert that the response is 200 - OK
        

        【讨论】:

        • 你介意把这里的代码格式化得更干净一点吗?另外,given() 应该是什么?
        • 嗨,这是rest-Assurd(测试rest Api)的基本用法。我在代码中添加了解释。
        【解决方案7】:

        第一步:获取HttpURLConnection对象

        URL url = new URL(urlToConnect);
        HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
        

        第 2 步:使用 setRequestProperty 方法将标头添加到 HttpURLConnection。

        Map<String, String> headers = new HashMap<>();
        
        headers.put("X-CSRF-Token", "fetch");
        headers.put("content-type", "application/json");
        
        for (String headerKey : headers.keySet()) {
            httpUrlConnection.setRequestProperty(headerKey, headers.get(headerKey));
        }
        

        参考link

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-12-14
          • 1970-01-01
          • 1970-01-01
          • 2010-10-03
          • 2018-12-17
          • 2017-09-05
          相关资源
          最近更新 更多