2016-09-06 13 views
0

HttpsURLConnection POSTリクエストからレスポンスを取得したいと考えています。 PostManでリクエストを実行しようとすると、応答として(es: 1520)という1つのメッセージが表示されます。私はこのコードを保存する必要がありますが、私はgetResponseCode()(200)またはgetResponseMessage()( "OK")の読み取り方法しか見つけません。私は別のライブラリを使うべきですか? HttpsUrlConnection方法で私は役に立つ何かを見つけることはありませんので(https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.htmlPOSTリクエストからレスポンスを取得

私のコードは次のとおりです。 WHILEループに到着したとき

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); 

    con.setSSLSocketFactory(sslContext.getSocketFactory()); 
    con.setDoOutput(true); 
    con.setUseCaches(false); 
    con.setRequestMethod("POST"); 
    con.setRequestProperty("Connection", "keep-alive"); 
    con.setRequestProperty("Content-Type", w_AECONTYP); 
    con.setRequestProperty("Accept-Charset", w_AEACCCHA); 
    con.setRequestProperty("Accept-Encoding", w_AEACCENC); 

StringBuilder postFile = new StringBuilder(); 
    byte[] postFileBytes =w_FileToSend.getBytes("UTF-8"); 
    con.setDoOutput(true); 
    try { 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.write(postFileBytes); 
    wr.flush(); 
    wr.close(); 
    } catch (Exception e) { 
    System.out.println("Connection Failed"); 
    e.printStackTrace(); 
    } 

    int responseCode = con.getResponseCode(); 
    // get 200 code "OK" 

     BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 

    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
    response.append(inputLine); 
    } 

    in.close(); 

しかし、それはサイクルに入りません。 どうすればいいですか? ファイルはJSON形式ですが、問題はありません。私は915のコードを保存する必要が

This is the screen shot of the same POST request with postman (chrome tool

!!

+0

このコードは200応答コードを生成しますか?私はDataOutputStreamのものを取り除き、URLがリダイレクトされていない限り、私のために働いているようです。 –

+0

はい200コードを生成します。しかし、while((inputLine = in.readLine())!= null)in.readLineはnullです! – Simone

+0

正しいURLと必要なヘッダー(ある場合)を渡していますか? URL obj =新しいURL(url); \t \t HttpsURLConnection con =(HttpsURLConnection)obj.openConnection(); – kuhajeyan

答えて

0

あなたは(レスポンスコードだけでなく)サーバからの応答を取得するためHttpResponseHttpPostを使用することができます。

HttpResponse httpResponse = httpClient.execute(new HttpPost(URL)); 
InputStream inputStream = httpResponse.getEntity().getContent(); 
InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
StringBuilder stringBuilder = new StringBuilder(); 
String bufferedStrChunk = null; 
while((bufferedStrChunk = bufferedReader.readLine()) != null){ 
    stringBuilder.append(bufferedStrChunk); 
} 
// now response is in the stringBuilder.toString() 

私は、これはあなたを助けることを願っています。

関連する問題