-1

I have a problem with this code I must do to make a connection to a php file with a post. Do I have to insert a thread? If yes, why? And where?

public class Login extends Activity {

    public String RispostaLogin;
    public String response,responseBody;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        Button pulsante = (Button) findViewById(R.id.button2);
        pulsante.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Log.d("myapp", "cliccato");
                sendPostRequest();


            }
        });


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

   public void sendPostRequest()
   {


       HttpClient httpclient = new DefaultHttpClient();
       HttpPost httppost = new HttpPost("https://api.uniparthenope.it/user/radius/auth");

       try {
           // Add your data
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
           nameValuePairs.add(new BasicNameValuePair("user", "user"));
           nameValuePairs.add(new BasicNameValuePair("passw", "pass"));
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

           // Execute HTTP Post Request
           HttpResponse response = httpclient.execute(httppost);

           responseBody=EntityUtils.toString(response.getEntity());


            Log.d("myapp", responseBody);



       } catch (ClientProtocolException e1) {
           e1.printStackTrace();
       } catch (UnsupportedEncodingException e1) {
           e1.printStackTrace();
       } catch (IOException e1) {
           e1.printStackTrace();
       }



   }
}
cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106
  • try this tutorial http://hmkcode.com/android-internet-connection-using-http-get-httpclient/ – Hasan Dec 07 '14 at 18:31
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – 323go Dec 07 '14 at 18:32
  • *If* you remembered to add the internet permission, you will certainly crash with `NetworkOnMainThreadException.` See linked question. – 323go Dec 07 '14 at 18:33

1 Answers1

-1

Let's point to a few things:

Android prevents you from doing an HttpConnection on the main thread. You can break this rule but it's not practical since the UI will freeze and user can't interact with your app. until the response receive.

To do an HttpConnection you need to get the internet permission by adding to your manifest file:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

To prevent the UI from getting froze during the HttpConnection run it on a background thread by using AsyncTask or Thread

I created an example that consumes your php file! on github. It is functional and tested on an android phone. it returns:

{
    "result": false
}

Just set the username and password correctly in the main activity class.

To allow http connection on main thread add the following couple of line to your onCreate method in your activity:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 
hasan
  • 23,815
  • 10
  • 63
  • 101
  • Because you should have started mentioning to use a thread or asynctask i think. Don't you think so? – greenapps Dec 09 '14 at 14:41
  • That's right. It's in the github project I created. but I forgot to mention it. I will now. – hasan Dec 09 '14 at 14:43
  • You still are not mentioning thread and AsyncTask here. And you still are advocating the use of StrictMode. You could as well have gotten two down votes for such an answer. – greenapps Dec 09 '14 at 14:58
  • well, as you wish. I did mention those. and I also gave him another option to run it on the UIThread thats why the StrictMode is there. cheers. – hasan Dec 09 '14 at 15:13