2017-04-09 493 views
0

我试图使用HttpURLConnection从我正在开发的Android应用程序连接到服务器。现在,我正在测试不是在应用程序中的连接代码,而是作为一个普通的Java程序与主类。我想这和HttpUrlConnection没有任何区别。HttpURLConnection总是失败401

请检查代码片段。另一个问题是即使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; 

}

回答

1

你可能会收到401因为被发送到服务器的凭据没有授权获它可能未注册或密码不正确。

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

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

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