小编典典

为 HttpURLConnection 添加标头

all

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

阅读 86

收藏
2022-04-22

共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

2022-04-22