如何在HTTP发布请求正文中发布参数?

use*_*773 3 android httpclient

我有一组参数,由用户输入并存储在此处:

 RequestParams params = new RequestParams();
 params.put("confirmPass", confirmPass);
 params.put("username", email);
 params.put("password", password);
Run Code Online (Sandbox Code Playgroud)

然后,我实例化AsyncHttpClient并实现所需的方法:

 AsyncHttpClient client = new AsyncHttpClient();
    client.get(url, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();

        }
    });
Run Code Online (Sandbox Code Playgroud)

如何发布存储在请求正文中的参数(我正在使用服务器(mocky.io)来模拟整个过程)?

ins*_*eof 5

怎么样:

public static String makePostRequest(String stringUrl, String payload, 
    Context context) throws IOException {
    URL url = new URL(stringUrl);
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    String line;
    StringBuffer jsonString = new StringBuffer();

    uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
    uc.setRequestMethod("POST");
    uc.setDoInput(true);
    uc.setInstanceFollowRedirects(false);
    uc.connect();
    OutputStreamWriter writer = new OutputStreamWriter(uc.getOutputStream(), "UTF-8");
    writer.write(payload);
    writer.close();
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        while((line = br.readLine()) != null){
            jsonString.append(line);
        }
        br.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    uc.disconnect();
    return jsonString.toString();
}
Run Code Online (Sandbox Code Playgroud)

有效负载是正文JSON字符串。您还需要使用AsyncTask并在doInBackground方法中运行上述方法,如下所示:

new AsyncTask<String, String, String>() {

    @Override
    protected String doInBackground(String... params) {
        try {
            String response = makePostRequest("http://www.example.com", 
                "{ exampleObject: \"name\" }", getApplicationContext());
            return "Success";
        } catch (IOException ex) {
            ex.printStackTrace();
            return "";
        }
    }

}.execute("");
Run Code Online (Sandbox Code Playgroud)

现在您也可以使用从服务器返回的响应