java - 为 HttpURLConnection 添加 header

标签 java http

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

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);
        }

最佳答案

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

关于java - 为 HttpURLConnection 添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43275382/

相关文章:

java - JBoss AS7.1.1 远程处理

java - 对象: no thread state can be involved,的序列化对吗?

performance - 对 HTTP/2 与以前的协议(protocol)版本进行基准测试

json - 带 API 的 Ruby 传递 header

http - 构建网络服务器,客户端不确认 HTTP 200 OK 帧

java - 我使用 RestTemplate 时不断收到 "Unsupported Media Type"错误

java - 从 JSOUP 解析的 HTML 中删除转义文本

JavaFX ChoiceBox 上下文菜单位置

http - 从 CloudWatch 流式传输日志数据

javascript - Angular js ng-click不起作用