2012-03-08 9 views
18

Come postare dati JSON utilizzando HttpURLConnection? Sto cercando in questo modo:cURL e HttpURLConnection - Post JSON Data

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(); 

sto ottenendo errore di compilazione in linea 14.

La richiesta è cURL:

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

È questo il modo di gestire la richiesta cURL? Qualsiasi informazione mi sarà molto utile.

Grazie.

+0

È necessario pubblicare l'errore di compilazione – ykaganovich

risposta

30

OutputStream prevede di lavorare con i byte e di trasmetterli ai personaggi. Prova questo:

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(); 
+0

Non è possibile inviare un oggetto JSON complesso in questo modo? Ad esempio ... "{" points ": [{" point ": {" latitude ": 40.8195085182092," longitude ": - 73.75127574479318}," description ":" test "}, {" point ": {" latitudine ": 40.2195085182092," longitudine ": - 74.75127574479318}," descrizione ":" test2 "}]," modalità ":" WALKING "}" ... è un oggetto che sto inviando tramite questo metodo e io ottenere un codice di risposta HTTP di 500. – crowmagnumb

+0

@CrowMagnumb È necessario inviare una domanda separata. 500 indica che il server ha un errore interno nel tentativo di elaborare la richiesta. – ykaganovich

+0

OK, ho fatto così [qui] (http://stackoverflow.com/questions/20452366/http-response-code-500-sending-complex-json-object-using-httpurlconnection) Grazie per il suggerimento. – crowmagnumb

8

Si consiglia di utilizzare la classe OutputStreamWriter.

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

quale sarebbe il vantaggio rispetto a 'OutputStream'? – Darpan