2016-07-08 4 views
0

この質問は何度も尋ねられました。私は数多くの例(Java - sending HTTP parameters via POST method easily)とブログをすべて成功せずに試してみました。AndroidはPOSTを使用してJSONを送信します

私はこの方法で私のサービスへの呼び出しを行うための

//POST 
public static void MakeRequest(String uri, String data, boolean isError) { 
    try { 
     Log.i(TAG, data); 
     Log.i(TAG, uri); 

     byte[] bytes =data.getBytes(); 
     // 2. make Connection 
     HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection())); 
     urlConnection.setRequestMethod("POST"); 
     urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
     urlConnection.setRequestProperty("charset", "utf-8"); 
     urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(bytes.length)); 
     urlConnection.setInstanceFollowRedirects(false); 
     urlConnection.setDoOutput(true); 
     urlConnection.setUseCaches (false); 

     DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); 
     wr.write(bytes); 

     Log.i(TAG, "after send?"); 
    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

を持っています。私がPostmanと一緒にテストしてきたので、サービスは正常に動作します。私のAndroid/Javaに関する知識が限られているため、上記のことがうまくいかない理由を理解するのが難しいです。私はデバッガを通ってきてエラーはスローされず、正しいURLが使用されます。 私が理解できないことは、サービスが決して到達していない理由です。

+0

あなたは 'wr.close()'を追加しようとしましたか? – Dimitris

+0

私は持っています。私はまた、接続を開こうとしました。 (urlConnection.connect())、おそらく必要はありません。私はフィドラーを発砲し、私が思ったようにそれはサービスに出ていない。 –

+0

data.getBytes(Charset.forName( "UTF-8"))を少し変更して、上記の行を追加したい場合があります。どのようなエラーが表示されますか? – Dimitris

答えて

0
URL loginUrl = new URL(Activity.getString(R.string.base_url) + "/users"); 
     HttpURLConnection loginConnection = (HttpURLConnection) loginUrl.openConnection(); 

     loginConnection.setRequestProperty("X-HTTP-Method-Override", "POST"); 
     loginConnection.setRequestMethod("POST"); 
     loginConnection.setRequestProperty("Content-Type", "application/json"); 
     loginConnection.setUseCaches(false); 
     loginConnection.setDoInput(true); 
     loginConnection.setDoOutput(true); 
     loginConnection.connect(); 

     JSONObject requestJson = new JSONObject(); 
     requestJson.put("username", username); 
     requestJson.put("email", email); 
     requestJson.put("password", password); 

     DataOutputStream printout = new DataOutputStream(loginConnection.getOutputStream()); 
     printout.writeBytes(requestJson.toString()); 
     printout.flush(); 
     printout.close(); 

これを使用してJSONオブジェクトを投稿します。これを要件に合わせて調整することができます。ヘッダーとURLをチェーン化し、別のオブジェクトを投稿します。

+0

これをコピーして調整しましたが、それでも機能しませんでした。エラーや何もありません。奇妙なことは、 "get"操作はうまくいくということです。私はとても困惑しています。 –

+0

どのようなエラーが表示されますか? –

関連する問題