Sending JSON to a server
I'm running the following Java, an HttpURLConnection PUT request with JSON data that will be sent from an Android device. I'll handle any raised exceptions after this is working. GET is working just fine.
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(nameString, pwdString.toCharArray());
}
});
url = new URL(myURLString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("PUT");
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream output = null;
try {
output = urlConnection.getOutputStream();
output.write(jsonArray.toString().getBytes());
} finally {
if (output != null) { output.close(); }
}
开发者_Go百科
int status = ((HttpURLConnection) urlConnection).getResponseCode();
System.out.println("" + status);
urlConnection.disconnect();
I'm receiving an HTTP 500 error (internal error code), that an unexpected property is blocking the request. The JSONArray comprises JSONObjects whose keys I know are correct. The server is pretty standard, and expects HTTP PUTs with JSON bodies.
Am I missing something?
first of all, I'd really recommend you to use Volley, a google API especially developed for HTTP(s) request using all of the request types (PUT,DELETE,POST,GET). I recommend you watching this: Video from Google I/O And following this tutorial (which covers your problem): Tutorial Link
If you decide to give it a try, just let me know and I'll be glad to help you!
See ya !
精彩评论