HttpURLConnection总是失败401

时间:2017-04-09 07:48:13

标签: java android httpurlconnection

我尝试使用HttpURLConnection从我正在开发的Android应用程序连接到服务器。现在,我不是在应用程序中测试连接代码,而是作为带有主类的普通java程序。我想这与HttpUrlConnection没什么区别。

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

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;

}

1 个答案:

答案 0 :(得分:1)

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

至于空错误流,请看一下这个SO answer

  

如果未连接连接,或者连接时服务器没有错误,或者服务器出现错误但未发送错误数据,则此方法将返回null。

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