Disapamok
Disapamok

Reputation: 1475

How to send http post request from Android?

I'm new to android and now I'm so tired of searching the best tutorial about android HTTP requests.

I'm trying to send these parameters to phpServer,

Can we do this in MainActivity.java file? is this need any jar(library) file? any suggestions are welcome.

I tried this,

@Override
public void onClick(View view) {
    if(view == btnSubscribe){
        HttpURLConnection client = null;
        try {
            URL url = new URL("http://www/somewebsite.com/API/SUBSCRIBE");
            client = (HttpURLConnection) url.openConnection();
            client.setRequestMethod("POST");
            client.setRequestProperty("name","test one");
            client.setRequestProperty("email","[email protected]");
            client.setDoOutput(true);

            OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
            outputPost.flush();
            outputPost.close();
            client.setChunkedStreamingMode(0);

        } catch(MalformedURLException error) {
            showError("Handles an incorrectly entered UR");
        }
        catch(SocketTimeoutException error) {
            showError("Handles URL access timeout");
        }
        catch (IOException error) {
            showError("Handles input and output errors");
        }finally {
            if(client != null)
            client.disconnect();
        }
    }
}

Upvotes: 1

Views: 12807

Answers (3)

Voltage Compong
Voltage Compong

Reputation: 1

Can confirm Jitendra ramoliya's answer is correct though it did not specify what 'data' is.

data there is a string where the first encoded value is the POST index and the second one is that index's value, separated by an '='.

This was not obvious at first and android documentation does not cover the data concatenation.

$_POST['Email'] is equivalent to URLEncoder.encode("Email", "UTF-8") with this method | and to add its value is

URLEncoder.encode("Email", "UTF-8") + "="
                    + URLEncoder.encode(email, "UTF-8")

Upvotes: 0

Jitendra
Jitendra

Reputation: 3698

I am using this code and working as well. Try this code.

public static String httpPostRequest(Context context, String url, String email) {
        String response = "";
        BufferedReader reader = null;
        HttpURLConnection conn = null;
        try {
            LogUtils.d("RequestManager", url + " ");
            LogUtils.e("data::", " " + data);
            URL urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

            data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
                    + URLEncoder.encode(email, "UTF-8");


            wr.write(data);
            wr.flush();

            LogUtils.d("post response code", conn.getResponseCode() + " ");

            int responseCode = conn.getResponseCode();



            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            response = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.d("Error", "error");
        } finally {
            try {
                reader.close();
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (Exception ex) {
            }
        }
        LogUtils.d("RESPONSE POST", response);
        return response;
    }

Upvotes: 7

Amit Bhati
Amit Bhati

Reputation: 1405

First, the most httpClint is deprecated now so if you can now use httpUrlConnection for the same.

you can refer to here

and if you want to use library then you can use

These two are the best library.

Cheers

Upvotes: 1

Related Questions