使用Java代码连接本地服务器时收到401响应码求助
Hey there! The 401 response you're seeing makes total sense—your Java code isn't sending the required authentication credentials to the server. Most simple password-protected local servers use Basic HTTP Authentication, so we need to add that to your request. Let's get this fixed right away:
Option 1: Manually Add the Authorization Header
This method directly inserts encoded credentials into your request headers, which is straightforward for one-off requests.
Since your server only specifies a password "12345", we can pair it with an empty username (adjust this if your server actually requires a specific username). We'll encode the credentials in Base64 format and attach them to the Authorization header.
Here's your modified code:
import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Base64; public class ServerConnector { public static void main(String[] args) { try { URL url = new URL("http://192.168.0.101:8080/"); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); // Set up Basic Authentication credentials String username = ""; // Update if your server requires a username String password = "12345"; String authCredentials = username + ":" + password; byte[] encodedAuth = Base64.getEncoder().encode(authCredentials.getBytes()); String authHeader = "Basic " + new String(encodedAuth); // Attach the authentication header to the request urlc.setRequestProperty("Authorization", authHeader); urlc.setRequestMethod("GET"); urlc.setConnectTimeout(10 * 1000); // 10-second timeout urlc.connect(); int responseCode = urlc.getResponseCode(); System.out.println("Response code: " + responseCode); if (responseCode == 200) { System.out.println("Connection success!"); } else { System.out.println("Connection failed with code: " + responseCode); } } catch (MalformedURLException e1) { System.out.println("MalformedURLException: Invalid URL format"); e1.printStackTrace(); } catch (IOException e) { System.out.println("IOException: Error connecting to the server"); e.printStackTrace(); } } }
Option 2: Use Authenticator for Reusable Authentication
If you plan to make multiple requests to the same server, using Authenticator is cleaner—it automatically applies credentials to all relevant requests without repeating header setup.
Add this snippet right before opening the connection:
Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // Use empty username + your password; update username if needed return new PasswordAuthentication("", "12345".toCharArray()); } });
Quick Notes:
- If your server uses a different authentication method (like Digest Auth), this Basic Auth approach won't work—but Basic Auth is the most common for simple local servers.
- I added
printStackTrace()to exception handlers to help you debug if something unexpected goes wrong. - Double-check if your server requires a specific username (some servers won't accept an empty one even if they only mention a password).
内容的提问来源于stack exchange,提问作者Kushal Bhalaik

