尝试连接本地服务器时收到“401”响应代码?
Getting "401" response code when trying to connect local server?
我有一个在 http://192.168.0.101:8080/ 上运行的本地服务器。每当我尝试使用以下代码对服务器执行 ping 操作时,我都会收到响应代码“401”。我的服务器要求密码为“12345”
try {
URL url = new URL("http://192.168.0.101:8080/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("GET");
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
System.out.println("code" + urlc.getResponseCode());
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
System.out.println("Connection success");
} else {
System.out.println("Connection nada");
}
} catch (MalformedURLException e1) {
System.out.println("MalformedURLException");
} catch (IOException e) {
System.out.println("IOException nada");
}
Http Status Code 401,表示未经授权的访问,您需要随请求一起发送 WWW-Authenticate
header。
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.
有不同的身份验证方案(即 Basic、Digest 或 OAuth),其中之一是 Basic 身份验证,如下所示。
//you code
//
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
urlc.setRequestProperty ("Authorization", basicAuth);
urlc.setRequestMethod("GET");
// your code
我有一个在 http://192.168.0.101:8080/ 上运行的本地服务器。每当我尝试使用以下代码对服务器执行 ping 操作时,我都会收到响应代码“401”。我的服务器要求密码为“12345”
try {
URL url = new URL("http://192.168.0.101:8080/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("GET");
urlc.setConnectTimeout(10 * 1000); // 10 s.
urlc.connect();
System.out.println("code" + urlc.getResponseCode());
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
System.out.println("Connection success");
} else {
System.out.println("Connection nada");
}
} catch (MalformedURLException e1) {
System.out.println("MalformedURLException");
} catch (IOException e) {
System.out.println("IOException nada");
}
Http Status Code 401,表示未经授权的访问,您需要随请求一起发送 WWW-Authenticate
header。
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field (Section 4.1) containing at least one challenge applicable to the target resource.
有不同的身份验证方案(即 Basic、Digest 或 OAuth),其中之一是 Basic 身份验证,如下所示。
//you code
//
String userCredentials = "username:password";
String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
urlc.setRequestProperty ("Authorization", basicAuth);
urlc.setRequestMethod("GET");
// your code