为HttpURLConnection添加标头

Min*_* Le 233 java http

我正在尝试为我的请求添加标头,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);
        }
Run Code Online (Sandbox Code Playgroud)

小智 394

我以前使用过以下代码,它在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);
Run Code Online (Sandbox Code Playgroud)

您可以尝试上面的代码.上面的代码用于POST,您可以为GET修改它

  • 当每个人都称它们为Headers时,为什么称它们为"RequestProperty"? (20认同)
  • Android开发人员的一点点补充(在API> = 8又称2.2):android.util.Base64.encode(userCredentials.getBytes(),Base64.DEFAULT); Base64.DEFAULT告诉使用RFC2045进行base64编码. (15认同)
  • 变量`postData`在哪里来自你的例子? (10认同)
  • Java8版本的一个附加功能:Base64类略有改动.解码应该使用:```string basicAuth ="Basic"+ java.util.Base64.getEncoder().encodeToString(userCredentials.getBytes());``` (2认同)

小智 16

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

encodedBytes = Base64.encode(authorization.getBytes(), 0);
authorization = "Basic " + new String(encodedBytes);
Run Code Online (Sandbox Code Playgroud)


小智 8

如果您使用的是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);
Run Code Online (Sandbox Code Playgroud)


gor*_*ori 5

终于这对我有用

private String buildBasicAuthorizationString(String username, String password) {

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

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

小智 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;
}
Run Code Online (Sandbox Code Playgroud)

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