web-dev-qa-db-fra.com

cURL et HttpURLConnection - Post JSON Data

Comment publier des données JSON en utilisant HttpURLConnection? J'essaye ceci:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

StringReader reader = new StringReader("{'value': 7.5}");
OutputStream os = httpcon.getOutputStream();

char[] buffer = new char[4096];
int bytes_read;    
while((bytes_read = reader.read(buffer)) != -1) {
    os.write(buffer, 0, bytes_read);// I am getting compilation error here
}
os.close();

Je reçois une erreur de compilation à la ligne 14.

La demande cURL est:

curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "{'value': 7.5}" \
"a URL"

Est-ce la façon de gérer la demande cURL? Toute information me sera très utile.

Merci.

18
Tapas Bose

OutputStream s'attend à fonctionner avec des octets et vous lui passez des caractères. Essaye ça:

HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();

byte[] outputBytes = "{'value': 7.5}".getBytes("UTF-8");
OutputStream os = httpcon.getOutputStream();
os.write(outputBytes);

os.close();
31
ykaganovich

Vous pouvez utiliser la classe OutputStreamWriter.

final String toWriteOut = "{'value': 7.5}";
final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(toWriteOut);
osw.close();
9
Anthony Chuinard