我是Android网络编程的新手,我想将一些Json格式的数据从android发布到服务器,并使用用于发布数据的相同HttpURLConnection
将响应返回到Android客户端。
这是我的邮政编码:
public void post() throws IOException {
URL url = createEndpointUrl();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(POST);
conn.setDoInput(true);
conn.setDoOutput(true);
String query = createQueryParameters();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
// Here i want to get operation
// result (response) from server
.
.
.
//
os.close();
conn.disconnect();
}
答案 0 :(得分:2)
获取回复:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
StringBuilder stringBuilder = new StringBuilder();
while ((decodedString = in.readLine()) != null) {
stringBuilder.append(decodedString);
}
in.close();
/*YOUR RESPONSE */
String response = stringBuilder.toString();
答案 1 :(得分:1)
尝试以下
public void post() throws IOException {
URL url = createEndpointUrl();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(POST);
conn.setDoInput(true);
conn.setDoOutput(true);
String query = createQueryParameters();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
// Here i want to get operation
// result (response) from server
.
.
.
//
os.close();
try {
int responseCode = conn.getResponseCode();// error code
String response = ""; // response
BufferedReader br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
br.close();
}catch(Exception e){
// handle error
}
conn.disconnect();
}