为HttpURLConnection添加标题


253

我正在尝试使用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);
        }

对我有用,您如何确定标头已发送而未收到?
Tomasz Nurkiewicz 2012年

1
抱歉,如果听起来很蠢,但是您connect()在URLConnection上调用什么位置?
维克多2012年

我不确定这是否有效,但是您可以尝试添加connection.setRequestMethod("GET");(或POST或任何您想要的内容)吗?
2012年

1
您初始化authorization为空字符串。如果usernamepassword为null,则为authorization空字符串,而不为null。因此,对我来说,最终if将被执行,但是该"Authorization"属性将被设置为空。
zerzevul

Answers:


422

我过去使用过以下代码,并且已在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


15
android开发人员的一些附加功能(API> = 8 aka 2.2):android.util.Base64.encode(userCredentials.getBytes(),Base64.DEFAULT); Base64.DEFAULT告诉使用RFC2045进行base64编码。
Denis Gladkiy 2013年

@Denis,请您告诉我为什么要使用标题。我必须从xammp上使用php的android验证一些凭据。我应该如何去做。因为我不知道如何用标头编写php代码
Pankaj Nimgade 2015年

11
postData您的示例中的变量来自哪里?
GlenPeterson '16

22
当每个人都将其称为标头时,为什么将它们称为“ RequestProperty”?
菲利普·雷哥

2
Java8版本的一个附加功能:Base64类有所更改。解码应使用:String basicAuth = "Basic " + java.util.Base64.getEncoder().encodeToString(userCredentials.getBytes());
Mihailo Stupar,

17

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

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

11

如果您使用的是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);

6

终于这对我有用

private String buildBasicAuthorizationString(String username, String password) {

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

2
@ d3dave。字符串是从字节数组创建的,并以“ Basic”串联。OP代码中的问题是他将“基本”与byte []连接起来,并将其作为标头发送。
yurin 2015年

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


1

使用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

1
您介意将代码格式化得更加干净吗?另外,given()应该是什么?
纳撒尼尔·福特

嗨,这是rest-Assurd(测试rest Api)的基本用法。我在代码中添加了解释。
Eyal Sooliman '17

-1

步骤1:获取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));
}

参考链接

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.