gpt4 book ai didi

java - HttpURLConnection 总是失败并显示 401

转载 作者:行者123 更新时间:2023-12-02 13:28:14 25 4
gpt4 key购买 nike

我正在尝试使用 HttpURLConnection 从我正在开发的 Android 应用程序连接到服务器。目前,我不是在应用程序中测试连接代码,而是将其作为带有主类的普通 java 程序进行测试。我想这对于 HttpUrlConnection 来说没有任何区别。

请检查代码 fragment 。另一个问题是 errorStream 甚至抛出 null。我觉得这是因为 URL 格式错误。

private static String urlConnectionTry() {
URL url; HttpURLConnection connection = null;

try {
String urlParameters = "email=" + URLEncoder.encode("email", "UTF-8") +
"&pwd=" + URLEncoder.encode("password", "UTF-8");
//Create connection
url = new URL("http://example.com/login");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("uuid", getUuid());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);

//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();

//Get Response
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}

}

private static String getUuid() {
try {
Document doc=Jsoup.connect("http://example.com/getUuid").get();
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
if(metaElem.attr("name").equals("uuid")) {
return metaElem.attr("content");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;

}

最佳答案

您可能收到 401,因为发送到服务器的凭据未经授权 - 它可能未注册或密码不正确。

至于空错误流,看看这个SO answer .

If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null.

如果您首先使用 HttpUrlConnection#getResponseCode() 检查响应代码,可能会更好。根据收到的响应代码决定是否检查错误流的内容。

关于java - HttpURLConnection 总是失败并显示 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43304309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com