Verifying login details via http get : Android

2019-08-30 08:01发布

问题:

I seem to be having a problem verifying user login details via http get:

Here is my code :

 public static void login(String userName, String password) {
    HttpClient httpclient = new DefaultHttpClient();


    // Prepare a request object
    HttpGet httpget = new HttpGet("http://reallinkhere/login/" + userName
                + "/" + password);

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
        // Examine the response status
        System.out.println(response.getStatusLine().toString());

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {

            // A Simple JSON Response Read
            InputStream instream = entity.getContent();
            String result= convertStreamToString(instream);
            Log.i(TAG,result);

            // A Simple JSONObject Creation
            JSONObject json=new JSONObject(result);
            Log.i(TAG,"<jsonobject>\n"+json.toString()+"\n</jsonobject>");

            // A Simple JSONObject Parsing
            JSONArray nameArray=json.names();
            JSONArray valArray=json.toJSONArray(nameArray);
            for(int i=0;i<valArray.length();i++)
            {
                Log.i(TAG,"<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
                        +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
            }

            // A Simple JSONObject Value Pushing
            json.put("sample key", "sample value");
            Log.i(TAG,"<jsonobject>\n"+json.toString()+"\n</jsonobject>");

            // Closing the input stream will trigger connection release
            instream.close();
        }


    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

and here is my logcat errors:

07-20 18:48:07.469: ERROR/AndroidRuntime(16013): FATAL EXCEPTION: main
    java.lang.IllegalStateException: Could not execute method of the activity
    at android.view.View$1.onClick(View.java:3599)
    at android.view.View.performClick(View.java:4204)
    at android.view.View$PerformClick.run(View.java:17355)
    at android.os.Handler.handleCallback(Handler.java:725)
    at android.os.Handler.dispatchMessage(Handler.java:92)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:5041)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    at dalvik.system.NativeStart.main(Native Method)
    Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at android.view.View$1.onClick(View.java:3594)
    ... 11 more
    Caused by: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    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 org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    at com.example.tempo.RestClient.login(RestClient.java:67)
    at com.example.tempo.MainActivity.onClickLogin(MainActivity.java:31)
    ... 14 more

i know the "reallinkhere" is correct and working as when i go to the link from the browser i get the following :

{"id":"2","email":"a","level":"3","first":"debug","last":
     "test","birth":"2013-07-19","lastlogin":"2013-07-20
     18:38:50","balance":"0.00"} 

回答1:

This exception occur when ever we are try to attempt network operation on UI thread.

   public class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
               // call function 
                login(userName, password);
                return null;
        }        

        @Override
        protected void onPostExecute(String result) {             
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

How to execute the task:

new LongOperation().execute();

Don't forget to add this to AndroidManifest.xml file:

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

Also see below link to more info:-

How to fix android.os.NetworkOnMainThreadException?

Caused by: android.os.NetworkOnMainThreadException



回答2:

You can't do HTTP transfers on the main thread. You need to run it in an AsyncTask or another thread.