问题
I'm trying to execute post request using HttpURLConnection but don't know how to do it correctly.
I can successfully execute request with AndroidAsyncHttp client using following code:
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.addHeader("Content-type", "application/json");
httpClient.setUserAgent("GYUserAgentAndroid");
String jsonParamsString = "{\"key\":\"value\"}";
RequestParams requestParams = new RequestParams("request", jsonParamsString);
httpClient.post("<server url>", requestParams, jsonHttpResponseHandler);
The same request can be performed using curl on desktop machine:
curl -A "GYUserAgentAndroid" -d 'request={"key":"value"}' '<server url>'
Both of this methods give me expected response from server.
Now I want to do the same request using HttpURLConnection. The problem is I don't know how to do it correctly. I've tried something like this:
URL url = new URL("<server url>");
HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("User-Agent", "GYUserAgentAndroid");
httpUrlConnection.setRequestProperty("Content-Type", "application/json");
httpUrlConnection.setUseCaches (false);
DataOutputStream outputStream = new DataOutputStream(httpUrlConnection.getOutputStream());
// what should I write here to output stream to post params to server ?
outputStream.flush();
outputStream.close();
// get response
InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line);
}
responseStreamReader.close();
String response = stringBuilder.toString();
JSONObject jsonResponse = new JSONObject(response);
// the response is not I'm expecting
return jsonResponse;
How to correctly write the same data as in working examples with AsyncHttpClient and curl to the HttpURLConnection output stream?
Thanks in advance.
回答1:
You can use the following to post the params
outputStream.writeBytes(jsonParamsString);
outputStream.flush();
outputStream.close();
回答2:
public String getJson(String url,JSONObject params){
try {
URL _url = new URL(url);
HttpURLConnection urlConn =(HttpURLConnection)_url.openConnection();
urlConn.setRequestMethod(POSTMETHOD);
urlConn.setRequestProperty("Content-Type", "applicaiton/json; charset=utf-8");
urlConn.setRequestProperty("Accept", "applicaiton/json");
urlConn.setDoOutput(true);
urlConn.connect();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
writer.write(params.toString());
writer.flush();
writer.close();
if(urlConn.getResponseCode() == HttpURLConnection.HTTP_OK){
is = urlConn.getInputStream();// is is inputstream
} else {
is = urlConn.getErrorStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
Log.e("JSON", response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return response ;
}
回答3:
Here you have a request using HttpUrlConnection, what you were missing was just read the value from the server.
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
InputStream is = null;
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
is = conn.getInputStream();// is is inputstream
} else {
is = conn.getErrorStream();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String response = sb.toString();
//HERE YOU HAVE THE VALUE FROM THE SERVER
Log.d("Your Data", response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
来源:https://stackoverflow.com/questions/20279195/android-post-request-using-httpurlconnection