3
JSONデータ(文字列として渡す)をサーバーに送信するコードです(このコードは、私が調べたところでdataJSON
の値として英語の文字を送信する場合に機能します):JSONデータをJavaのPOST経由で送信する
private static String sendPost(String url, String dataJSON) throws Exception {
System.out.println("Data to send: " + dataJSON);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String type = "application/json;charset=utf-8";
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Length", String.valueOf(dataJSON.getBytes("UTF-8").length));
con.setRequestProperty("Content-Type", type);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeUTF(dataJSON);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.print("Response string from POST: " + response.toString() + "\n");
return response.toString();
}
問題点私は、例えばDHC Restlet Clientを使用して得られる正しい応答を得られません。
問題は私がdataJSON
をUTF8でエンコードする必要があると思います。それはサーバーがそれを最も期待する方法です。 しかし、私はそれを変換して送信しようとする方法でコードにいくつかの問題があるようです。 上記の例でUTF8文字列として本文にデータを送信するのに役立つ人はいますか?