且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过HTTP GET验证登录信息:Android版

更新时间:2023-12-03 20:39:40

此异常发生时,以往我们正在尝试在UI线程尝试网络操作。

 公共类LongOperation扩展的AsyncTask<弦乐,太虚,字符串> {        @覆盖
        保护字符串doInBackground(字符串... PARAMS){
               //通话功能
                登录(用户名,密码);
                返回null;
        }        @覆盖
        保护无效onPostExecute(字符串结果){
        }        @覆盖
        在preExecute保护无效(){
        }        @覆盖
        保护无效onProgressUpdate(虚空......值){
        }
    }

如何执行任务:

 新LongOperation()执行();

不要忘了将它添加到AndroidManifest.xml文件:

 <使用许可权的android:NAME =android.permission.INTERNET对/>

另请参见下面链接的详细信息: -

android.os.NetworkOnMainThreadException

Caused由:android.os.NetworkOnMainThreadException

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"} 

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:-

android.os.NetworkOnMainThreadException

Caused by: android.os.NetworkOnMainThreadException