我正在尝试通过基本身份验证创建一个连接到服务器的程序,但是当我尝试设置“授权”HTTP标头出错时,因为当我尝试显示插入的标头时,没有“授权”标头我的HTTP请求,有人知道为什么吗? 这是我的代码:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.DatatypeConverter;
public class Esse3Connection {
public static void main(String[] args) {
try {
String webPage = "http://192.168.1.1:80";
String name = "admin";
String password = "admin";
String authString = name + ":" + password;
System.out.println("auth string: " + authString);
String authEncBytes = DatatypeConverter.printBase64Binary(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
urlConnection.connect();
System.out.println(urlConnection.getRequestProperty("Authorization"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
尝试替换:
byte[] encoding = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(encoding);
import org.apache.commons.codec.binary.Base64;