-3

This is where my HttpURLConnection is being held. I am trying to send the username/password over to my php control, which returns a true/false result.

However when I added Buffered Reader I kept getting the same error over and over.

I have seen this post, but I still don't understand. Can someone explain why this doesn't work?

METHOD:

public boolean checkLogin(String username, String password){
    boolean is_Correct = false;
    try {
        URL url = new URL(this.url);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
        output.write("func=Login");
        output.write("username="+username);
        output.write("password="+password);
        BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
        String result = input.readLine();
        output.flush();
        output.close();
    }catch(Exception e){
        e.printStackTrace();
    }
    return is_Correct;
}

ERROR:

09-19 12:25:27.408 3913-3913/com.project.backgroundprocesstest W/System.err: android.os.NetworkOnMainThreadException
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:436)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:399)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:379)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:369)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:287)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:261)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.HttpConnect$override.checkLogin(HttpConnect.java:38)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.HttpConnect$override.access$dispatch(HttpConnect.java)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.HttpConnect.checkLogin(HttpConnect.java:0)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.LoginControl.checkLogin(LoginControl.java:13)
09-19 12:25:27.410 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.MainActivity$1$override.onClick(MainActivity.java:52)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.MainActivity$1$override.access$dispatch(MainActivity.java)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.project.backgroundprocesstest.MainActivity$1.onClick(MainActivity.java:0)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.view.View.performClick(View.java:5210)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.view.View$PerformClick.run(View.java:21328)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.os.Looper.loop(Looper.java:148)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5551)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
09-19 12:25:27.411 3913-3913/com.project.backgroundprocesstest 
Community
  • 1
  • 1
atanti
  • 57
  • 7
  • Create a `new Thread()` and do your networking their. – Enzokie Sep 19 '16 at 10:40
  • 1
    Possible duplicate of [How to fix android.os.NetworkOnMainThreadException?](http://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception) – K Neeraj Lal Sep 19 '16 at 10:41
  • Thanks for the link, I think this is my problem. – atanti Sep 19 '16 at 10:43
  • 1
    `output.write("username="+username);`. That should be `output.write("&username="+username);`. Like for the following. – greenapps Sep 19 '16 at 10:49
  • `which returns a true/false result.` Php can not return boolean values. Moreover your script is not reached at all at the moment. – greenapps Sep 19 '16 at 10:51
  • Also, I don't see anywhere where you are actually checking the result. Your 'result' variable is a String that you never use... and your function returns a boolean that you never set. – Nerdy Bunz Sep 19 '16 at 10:53
  • @greenapps You were right. I change it into one line and it worked. I also forgot to add the StrickMode.ThreadPolicy (the fault of the error). – atanti Sep 19 '16 at 11:18
  • @BooberBunz It had nothing to do with the error, that was just incomplete code. – atanti Sep 19 '16 at 11:18
  • `I also forgot to add the StrickMode.ThreadPolicy`. DO NOT USE THAT!. Put your code in an AsyncTask or Thread instead. As Boober Bunz already told you. – greenapps Sep 19 '16 at 11:55
  • Why shouldn't I use it ? Just asking. – atanti Sep 20 '16 at 20:02

1 Answers1

1

As has been mentioned, you need to use asynctask. Inside that asynctask, you could also improve your communication with your php by putting your parameters in a HashMap and using a method like this:

public String performPostCall(String requestURL, HashMap<String, String> postDataParams)
{
    String response = "Network Error.";

   // Log.i(TAG, "performpostcall was run!! yay!");
    try
    {
        URL url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setReadTimeout(8000);
        conn.setConnectTimeout(8000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));

        writer.write(getPostDataString(postDataParams));

      //  Log.i(TAG, "getPostDataString() returned " + getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();
        if (responseCode == 200)
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                response = response + line;
            }
        }
        else
        {
            response = "response code: " + responseCode;

        }
        conn.disconnect();
    }
    catch (Exception e)
    {
        //  This should never happen. :)
    }
    return response;
}

and...

private String getPostDataString(HashMap<String, String> params)
        throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

   // Log.i(TAG, "get PostDataString was run!! yay!");
    for (Map.Entry<String, String> entry : params.entrySet())
    {
        if (first) {
            first = false;
        } else {
            result.append("&");
        }
        result.append(URLEncoder.encode((String)entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode((String)entry.getValue(), "UTF-8"));
    }
    return result.toString();
}

This way you can control your timeouts, set your parameters easily, and get more detailed information about the causes of any errors.

Nerdy Bunz
  • 6,040
  • 10
  • 41
  • 100