55

私はすでに HTTPUrlConnection を作成しました:

String postData = "x=val1&y=val2";
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Set-Cookie", sessionCookie);
conn.setRequestProperty("Content-Length", "" + Integer.toString(postData.getBytes().length));

// How to add postData as http body?

conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

httpボディにpostDataを設定する方法がわかりません。その方法は?HttpPost代わりに使ったほうがいいですか?

ご協力いただきありがとうございます。

4

2 に答える 2

85

文字列のみを送信する場合は、次の方法を試してください。

String str =  "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );    
os.close();

ただし、Json として送信する場合は、コンテンツ タイプを次のように変更します。

conn.setRequestProperty("Content-Type","application/json");  

そして今、私strたちは次のように書くことができます:

String str =  "{\"x\": \"val1\",\"y\":\"val2\"}";

それが役立つことを願って、

于 2013-11-16T16:47:25.377 に答える