3

I have a set of the params, entered by the user and stored here:

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

Then I instantiate the AsyncHttpClient and implement the required methods:

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

        }
    });

How can I POST the params stored in the body of the request (I am using a server (mocky.io) to mock the whole process)?

user6456773
  • 381
  • 2
  • 10
  • 18
  • Have you tried HttpURLConnection and getOutputStream()? – instanceof Jun 17 '16 at 06:54
  • refer this link http://stackoverflow.com/a/13901661/6390538 – Divyesh Boda Jun 17 '16 at 06:54
  • I'm not sure what you mean by "POST the params stored in the body of the request". If you want to make a post request with the parameters you can just use `client.post(getAbsoluteUrl(url), params, responseHandler);` – Kairat Jun 17 '16 at 06:58

3 Answers3

5

How about:

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

Where payload is the body JSON string. You will also need to use an AsyncTask and run the above method in the doInBackground method, like so:

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

Now you can use the response you get back from the server as well

instanceof
  • 1,404
  • 23
  • 30
  • Thanks for the idea. So, having the method, I invoke in the onSuccess? Something like this? makePostRequest(url,"name:name,email:email",getApplicationContext()); – user6456773 Jun 17 '16 at 08:04
  • Okey, it's getting clearer :) The AsyncTask i put in the onSuccess, or I don't need to use AsyncHttpClient anymore? What I am trying to do is bost the body of the resuest in mocky.io. Thanks a lot for the help! – user6456773 Jun 17 '16 at 08:27
  • You don't have to use AsyncHttpClient anymore :) – instanceof Jun 17 '16 at 08:38
0

you can do it like this

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

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

        }
shivpal jodha
  • 104
  • 1
  • 9
0

Why don't you use Volley if you are new to android. Its much Simpler and doesn't require an Asycntask etc.

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);
Yash Jain
  • 376
  • 1
  • 3
  • 13
  • Thanks a lot for the suggestion! The problem, for me, comes from the mock I need to implement. What I am doing so far - using http://www.mocky.io/, generating an empty request and giving the parameter of the request as URL in my code. My approach could be completely worng, but what I need to achieve is to post the info, collected from the user, in the body of the server POST request. – user6456773 Jun 17 '16 at 07:21