-2

Please share good answer for POST Request with key,value pair params using HttpUrlConnection. The login screen has username, password field, the values need to post server and get json response with status "TRUE". don't want to use Volley Library.
Please answer in Detail or share a link, thank u.

pavan kvch
  • 129
  • 1
  • 12
  • 4
    What you have tried on your own ? Or else do `Google.com`. – Jay Rathod RJ Mar 31 '16 at 06:29
  • 2
    you entered `stackoverflow.com` as url in place of `Google.com` in your browser – Vivek Mishra Mar 31 '16 at 06:50
  • @jaydroider i tried with HashMap params it works very fine. But I dont know whether it is correct way or not. Searched so many tutorials they use deprecated HttpClient. please share perfect answer or link – pavan kvch Mar 31 '16 at 07:09

4 Answers4

3

Prepare a string request by following code :

Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", edit_username.getText().toString())
                        .appendQueryParameter("password", edit_password.getText().toString());

                    String query = builder.build().getEncodedQuery();

Perform web service all in async task by following code :

class AsyncLoad extends AsyncTask<Void,Void,Void>
{

    InputStream inputStream;
    HttpURLConnection urlConnection;
    byte[] outputBytes;
    String query;
    String ResponseData;

    public AsyncLoad(String query) {
        this.query = query;
    }

    @Override
    protected Void doInBackground(Void... params) {

        // Send data
        try {

        /* forming th java.net.URL object */
            URL url = new URL("your webservice url");
            urlConnection = (HttpURLConnection) url.openConnection();


            /* pass post data */
            outputBytes = query.getBytes("UTF-8");

            urlConnection.setRequestMethod("POST");
            urlConnection.connect();
            OutputStream os = urlConnection.getOutputStream();
            os.write(outputBytes);
            os.close();

        /* Get Response and execute WebService request*/
            int statusCode = urlConnection.getResponseCode();

        /* 200 represents HTTP OK */
            if (statusCode == HttpsURLConnection.HTTP_OK) {

                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                ResponseData= convertStreamToString(inputStream);

            } else {

                ResponseData = null;
            }


        } catch (Exception e) {

            e.printStackTrace();

        }



        return null;
    }
}

Call AsynctTask by following line :

  new AsyncLoad(query).execute(); // You have pass your request here

Convert response to String :

public static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
Harshal Bhatt
  • 711
  • 10
  • 23
  • what is outputBytes? can i put request code in method or class, how to pass query to that method,please answer in detail. I accept your answer – pavan kvch Mar 31 '16 at 07:21
  • declare byte[] outputBytes variable globally. You can pass query to your async class by passing parameter using constructer. You can read about how to use async task here : http://developer.android.com/intl/zh-cn/reference/android/os/AsyncTask.html – Harshal Bhatt Mar 31 '16 at 07:23
  • edit u r answer where to put try class block in AsyncTask or method, pass query to that class, declare byte[], It will helpful to someone, thank u – pavan kvch Mar 31 '16 at 07:31
  • @pavankvch check the answer i edited. – Harshal Bhatt Mar 31 '16 at 08:42
2
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     new AsyncCaller().execute();
}


private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
    ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("Loading...");
        pdLoading.show();
    }
    @Override
    protected Void doInBackground(Void... params) {

         String address = "http://server/postvalue";
            JSONObject json = new JSONObject();                
            json.put("username", username);
            json.put("password", password);
            String requestBody = json.toString();
            URL url = new URL(address);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();

            InputStream inputStream;
            // get stream
            if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                inputStream = urlConnection.getInputStream();
            } else {
                inputStream = urlConnection.getErrorStream();
            }
            // parse stream
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String temp, response = "";
            while ((temp = bufferedReader.readLine()) != null) {
                response += temp;
            }

            return response.toString();

        } catch (IOException | JSONException e) {
            return e.toString();
        }

    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);             
        pdLoading.dismiss();
        Log.i(LOG_TAG, "POST\n" + result);
    }

    }
}
Android Geek
  • 7,328
  • 2
  • 17
  • 32
0

You can use Http Client from Apache Commons. For example:

private class PostTask extends AsyncTask<String, String, String> {
      @Override
      protected String doInBackground(String... data) {
        // Create a new HttpClient and Post Header

    HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://<ip address>:3000");

        try {
          //add data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
          nameValuePairs.add(new BasicNameValuePair("data", data[0]));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          //execute http post
          HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }
      }
    }
crashOveride
  • 811
  • 6
  • 12
0
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(register_user);
    JSONObject jsonObject=new JSONObject();
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    try {

       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("username", username.getText().toString())); 
       params.add(new BasicNameValuePair("password",password.getText().toString())); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 


        HttpResponse response=httpClient.execute(httpPost);


        if(response!=null){
            InputStream is=response.getEntity().getContent();
            BufferedReader bufferedReader=new BufferedReader(new     InputStreamReader(is));
            StringBuilder sb=new StringBuilder();
            String line=null;
            while((line=bufferedReader.readLine())!=null){
                sb.append(line+"\n");
            }
            this.message=sb.toString();
            //Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG).show();
        }

    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
pamitha
  • 55
  • 1
  • 5