2017-04-09 30 views
0

開発中のAndroidアプリからサーバーに接続するためにHttpURLConnectionを使用しようとしています。今のところ、アプリケーションではなくメインクラスのプレーンなJavaプログラムとして接続コードをテストしています。私はこれまでHttpUrlConnectionと違いはないと思います。HttpURLConnectionは常に401で失敗する

コードスニペットを確認してください。別の問題は、errorStreamがnullを投げていることさえあります。これは私が気付いているのは、不正な形式のURLだからです。サーバーに送信された資格情報が、それはおそらく登録されていないauthorized-されていないか、パスワードが正しくないため、

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をご覧ください。

接続が接続されていない場合、または接続中にサーバーにエラーがない場合、またはサーバーにエラーがあってもエラーデータが送信されなかった場合、このメソッドはnullを返します。

HttpUrlConnection#getResponseCode()を使用して最初に応答コードを確認した方が良いでしょう。取得したレスポンスコードに基づいてエラーストリームの内容をチェックするかどうかを決定します。

関連する問題