2017-04-09 492 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()檢查響應代碼,那麼可能會更好。根據您獲得的響應代碼決定是否要檢查錯誤流的內容。