如何在HTTP post请求的主体中发布params?

时间:2016-06-17 06:48:49

标签: android httpclient

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

 RequestParams params = new RequestParams();
 params.put("confirmPass", confirmPass);
 params.put("username", email);
 params.put("password", password);

然后我实例化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();

        }
    });

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

3 个答案:

答案 0 :(得分: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();
}

其中payload是body 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("");

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

答案 1 :(得分:0)

你可以这样做

       u = Configa.COMMON_URL+"/login.html";

        DefaultHttpClient httpClient = new DefaultHttpClient();
        // HttpGet httpGet = new HttpGet(url);
        HttpPost httpPost = new HttpPost(u);
        List<NameValuePair> nameValuePairs = new
                ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("uname",usernm));
        nameValuePairs.add(new BasicNameValuePair("pwd",userPwd));
        nameValuePairs.add(new BasicNameValuePair("loginCompanycode",cmp));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      /*  HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        retStr = EntityUtils.toString(httpEntity);*/
        try {
        HttpResponse response= httpClient.execute(httpPost); // some response object
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();
            Log.d("shiv", "valeLogin:" + json);
        JSONTokener tokener = new JSONTokener(json);

或与Asynic Task

       public class TrainingHistorygettask extends AsyncTask<String,Void, List<Object>>
{
    Dialog dialogc;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialogc = new Dialog(TrainingHistory.this);
        dialogc.setCancelable(false);
        dialogc.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialogc.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialogc.show();
        setProgressBarIndeterminateVisibility(true);
    }
    @Override
    protected List<Object> doInBackground(String... params) {

        // TODO Auto-generated method stub
        RestTemplate restTemplate = new RestTemplate();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(TrainingHistory.this);
        String cookieValue = preferences.getString("Set-Cookie","");

        HttpHeaders requestHeaders = new HttpHeaders();
        List<MediaType> acceptableMediaTypes = new
                ArrayList<MediaType>();
        acceptableMediaTypes.add(MediaType.APPLICATION_JSON);

        requestHeaders.setAccept(acceptableMediaTypes);
        //requestHeaders.add("Content-Type", "");
        requestHeaders.add("Cookie",cookieValue);


        HttpEntity<?> requestEntity =new HttpEntity<Object>(requestHeaders);
        try{
            List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
            messageConverters.add(new StringHttpMessageConverter());
            messageConverters.add(new MappingJacksonHttpMessageConverter());
            restTemplate.setMessageConverters(messageConverters);
        }
        catch(Exception e)
        {
            System.out.println("Error "+e);
        }
        try
        {
            ResponseEntity<Object[]> responseEntity =
                    restTemplate.exchange(
                            params[0],
                            HttpMethod.POST, requestEntity,
                            Object[].class);

            return Arrays.asList(responseEntity.getBody());
        }
        catch (Exception e) {
            System.out.println("Error "+e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<Object> responseData){
        if(dialogc.isShowing()){
            dialogc.dismiss();

        }

答案 2 :(得分:0)

如果你是Android的新手,为什么不使用Volley。它更简单,不需要Asycntask等。

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>() {
@Override
public void onResponse(String response) {
    // Display the first 500 characters of the response string.
    mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
    mTextView.setText("That didn't work!");
}
}){

 Map getParameters(){
  Map map=new Hashamp()<String,String>;
  //ADD POST DATA TO MAP
  return map;
 }

};
// Add the request to the RequestQueue. 
queue.add(stringRequest);