2016-05-24 15 views
0

doInBackgroundメソッド内のAsync TaskでHttpUrlConnectionクラスを使用しようとしています。HttpUrlConnection内でPOSTメソッドを使用する方法

@Override 
    protected String doInBackground(String... params) { 
     String strUrl=String.format("%s",SERVER_URL); 
     try { 

      URL url =new URL(strUrl); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("POST"); 
      urlConnection.setDoOutput(true); 
      urlConnection.setDoInput(true); 
      urlConnection.setChunkedStreamingMode(0); 
      urlConnection.setRequestProperty("Content-Type","application/json"); 

      String str="{\"userid\":\"1\"}"; 
      byte[] outputInBytes = str.getBytes("UTF-8"); 
      OutputStream os = urlConnection.getOutputStream(); 
      os.write(outputInBytes); 
os.close(); 


      InputStream stream1=urlConnection.getInputStream(); 
InputStreamReader reader = new InputStreamReader(stream1); 
     StringBuilder builder = new StringBuilder(); 
     int chr; 
     while((chr=reader.read())!=-1) 
     { 
      builder.append((char)chr); 
     } 
     String result=builder.toString(); 

return result; 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
return null; 
    } 

しかし、私は結果の代わりにnullを取得していますが、ここで問題になるでしょう。私たちのURLは、特定のパケットにチャンクを取得この方法により

- :

+0

コードをデバッグしてコードフローを確認してください –

+0

これを取得と送信の両方に使用できますhttp://stackoverflow.com/questions/37289109/calling-a-async-task-and-waiting-for-answer? noredirect = 1#comment62106624_37289109 –

+0

あなたはサーバーコードまたは結果でnullを取得していますか?、結果の値はサーバーが応答するものになります。 –

答えて

0

最後に私のコードはうまく動作しますが、それはのようないくつかの変更を必要とします。

urlConnection.setChunkedStreamingMode(0);//No use in my code 

私が代わりに「アプリケーション/ JSON」の簡単なString.Soとして扱われるJSONのハードコードされた文字列を、使用していたように、私は「アプリケーション/ x-www-form-urlencodedで」使用することをしました以下に示すように。

urlConnection.setRequestProperty("Content-Type","application/json");//incorrect 
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");//when we need to pass string inside POST body. 

POSTメソッドURLに接続するためのものです。

私が間違った概念をどこかに持っていたら、教えてください。

関連する問題