Mattia Frusca
Mattia Frusca

Reputation: 45

Android Http POST request doesen't work

I have this Android code :

package com.example.webtestconnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    private Button login;
    private EditText username, password;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        login = (Button) findViewById(R.id.ok);
        username = (EditText) findViewById(R.id.name);
        password = (EditText) findViewById(R.id.password);

        login.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                String   mUsername = username.getText().toString();
                String  mPassword = password.getText().toString();

                tryLogin(mUsername, mPassword);
            }
        });
    }

    protected void tryLogin(String mUsername, String mPassword)
    {
        HttpURLConnection connection;
        OutputStreamWriter request = null;

        URL url = null;
        String response = null;
        String parameters = "username="+mUsername+"&password="+mPassword;

        try
        {
            url = new URL("http://welovelamacompany.altervista.org/test2.php");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestMethod("POST");

            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            // Response from server after login process will be stored in response variable.
            response = sb.toString();
            // You can perform UI operations here
            Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show();
            isr.close();
            reader.close();

        }
        catch(IOException e)
        {
            // Error
        }
    }
}

And this is the php page code:

<?php
//impostazioni server phpmyadmin per poter accedere al db
    $servername = "servername";
    $username = "username";
    $password = "password";
    $databasename = "my_databasename";
    $Nome_Giocatore = $_POST['username'];
    $PasswordGiocatore = $_POST['password'];
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$databasename", $username, $password);
        //imposto una modalità di eccezzione errore
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        //stampo che la connessione è riuscita
        $sql=$conn->query("SELECT Password_Giocatore FROM Giocatori WHERE Nome_Giocatore=\"$Nome_Giocatore\"");
        $control = $sql->fetch();
        $controllo=$control['Password_Giocatore'];
        if (password_verify($PasswordGiocatore, $controllo)){
            echo "Success";
        } else {
            echo "Error";
        }
        $conn->exec($sql);
    } catch(PDOException $e){
                    //stampo che la connessione è fallita e l'errore che ha causato il fallimento
                    echo "Qualcosa è andato storto :(. Errore: <br/>".$e->getMessage();
                }
    $conn = null;
?>

But when I run it it give me this error:

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.webtestconnection, PID: 23550 android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166) at java.net.InetAddress.lookupHostByName(InetAddress.java:385) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) at java.net.InetAddress.getAllByName(InetAddress.java:214) at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28) at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216) at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122) at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:390) at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:343) at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289) at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89) at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197) at com.example.webtestconnection.MainActivity.tryLogin(MainActivity.java:62) at com.example.webtestconnection.MainActivity$1.onClick(MainActivity.java:40) at android.view.View.performClick(View.java:4633) at android.view.View$PerformClick.run(View.java:19270) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5476) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method)

Why? How can I fix it? Thanks for help

P.S. I have the internet permission in the manifest

Upvotes: 0

Views: 91

Answers (2)

Abdul Aleem
Abdul Aleem

Reputation: 729

Please use AsyncTask to make an API call, you are getting exception because you are calling it on MainThread.

class LoginTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    protected YourResponse doInBackground(String... urls) {
        try {
             URL url = new URL(urls[0]);
            //your login code
        } catch (Exception e) {
            this.exception = e;
        } 
    }
    protected void onPostExecute(YourResponse response) {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

and add this line in your code

new LoginTask().execute(url);

EDITED You can below libraries for Network calls, easier and optimized for Network calls

  1. Retrofit
  2. Volley

Upvotes: 2

balsick
balsick

Reputation: 1201

You are trying to run a http connection on the main thread. This in Android is absolutely forbidden, because you undermine the app's responsiveness. You should run your connection into an AsyncTask

Upvotes: 0

Related Questions