0

I'm new to Android development, and I need to send a pretty basic HTTP POST request to a PHP server, and came across this method:

protected void performRequest(String name, String pn) {
    String POST_PARAMS = "name=" + name + "&phone_number=" + pn;
    URL obj = null;
    HttpURLConnection con = null;
    try {
        obj = new URL("theURL");
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");

        // For POST only - BEGIN
        con.setDoOutput(true);
        OutputStream os = con.getOutputStream();
        os.write(POST_PARAMS.getBytes());
        os.flush();
        os.close();
        // For POST only - END

        int responseCode = con.getResponseCode();
        Log.i(TAG, "POST Response Code :: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) { //success
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // print result
            Log.i(TAG, response.toString());
        } else {
            Log.i(TAG, "POST request did not work.");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

But when I run this the app crashes, saying:

FATAL EXCEPTION: main
Process: (the app id), PID: 11515
android.os.NetworkOnMainThreadException

As much as I understood, I need to perform this on a background thread, is there a relatively simple way to do it?

Also, I've seen a method to send post request using HttpClient, but it seems to be deprecated. Is it still usable nonetheless?

Thanks in advance!

Mitt
  • 9
  • 1
  • Duplicate post. There are tons of other posts on this. You need to make the Network Call on an Asynctask instead of the UI thread. Please look it up. – Actiwitty Aug 31 '15 at 18:20
  • 1
    you'll notice answers to this questions have existed for more than 4 years. – njzk2 Aug 31 '15 at 18:29

3 Answers3

1

Probably you are making the request in main thread. I suggest you using library like retrofit for the requests its much simplier.

Gjoko Bozhinov
  • 1,137
  • 11
  • 15
  • 1
    Agreed - retrofit (or other similar networking libraries) are much more reliable than trying to reinvent the wheel – Andrew Breen Sep 01 '15 at 00:57
0

You should use AsyncTask class . Android simply won't allow users to perform long running networking operations on main thread. This will block the thread. And hence will not allow the program to function properly. Here are some references. http://developer.android.com/reference/android/os/AsyncTask.html

http://www.youtube.com/watch?v=B25Nx48JuVo

Panda
  • 2,400
  • 3
  • 25
  • 35
0

You're right, you need to do this in a background task. The easiest way is to use AsyncTask. Here is a quick template on how to do it:

 private class PostTask extends AsyncTask<Void, Void, HttpResponse> {

     String POST_PARAMS;
     Activity activity;
     public PostTask(Activity activity, String params) {this.POST_PARAMS = params, this.activity = activity}

     protected Long doInBackground(Void... params) {
         HttpPost httpPost = new HttpPost("theURL");
         httpPost.setEntity(new StringEntity(POST_PARAMS));
         HttpResponse response;
         response = client.execute(httpPost);

     }

     protected void onPostExecute(HttpResponse response) {
         // Parse the response here, note that this.activity will hold the activity passed to it
     }
 }

Whenever you want to run it, just call new PostTask(getActivity(),PARAMS).execute()

asiviero
  • 1,225
  • 10
  • 16
  • Ok, and how do I get the response to the main thread and use it? – Mitt Aug 31 '15 at 18:58
  • you should probably do the computation needed by that in the `onPostExecute`, since it is run in the UI thread – asiviero Aug 31 '15 at 19:04
  • But it is in a different class (?) How do I get the response to the activity? (Sorry if I sound dumb, I really don't understand much in Android development) – Mitt Aug 31 '15 at 19:13
  • you mean there are properties in your activity that needs to be modified after the request is done? – asiviero Aug 31 '15 at 19:16
  • Yes, I get JSON from the request and need to use it in the activity (fragment to be exact) – Eilon Aug 31 '15 at 20:08
  • you could pass the activity as a parameter to the Task, I'll edit my answer to include it – asiviero Aug 31 '15 at 20:10