Post Json 从 android 客户端到服务器并得到响应

Post Json from android client to server and get response

我是 android 网络编程的新手,我想 post 一些 Json 格式的数据从 android 到服务器并得到响应 android 客户端使用与 post 数据相同的 HttpURLConnection

这是我的 post 代码:

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

获取响应:

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

试试下面

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