-2

我有关于我的 android 客户端的问题。

我有一个脚本,它使用一个安静的 web 服务并确定用户身份验证这是我的代码

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;  
import org.apache.http.client.HttpClient;  
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;  
import org.apache.http.impl.client.DefaultHttpClient; 

import android.os.AsyncTask;
import android.util.Log;

public class RestLogin {

private static String URL = "http://REST Webservice here?";
private static final String tag = "Logcat tag: ";


public static Boolean Auth(String username,String password)
{
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL);
    //adding parameter to request to determine user authentication
    request.addHeader("username",username);
    request.addHeader("password",password);
    //taking handler to get execution status
    ResponseHandler<String> handler = new BasicResponseHandler();
    try
    {
        result = httpclient.execute(request, handler);
    }

        catch (ClientProtocolException cpe)
        {
            cpe.printStackTrace();
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
        catch(IllegalArgumentException iae)
        {
            iae.printStackTrace();
        }
        catch(NullPointerException npe)
        {
            npe.printStackTrace();
        }

    httpclient.getConnectionManager().shutdown();
    Log.i(tag,result);
    return Boolean.parseBoolean(result);        
}

}

首先,当我构建代码时,它在我的 logcat 状态上显示错误 NetworkOnMainThreadException。然后,我发现由于google android honeycomb,我不能直接使用这种方法。所以我需要添加 AsyncTask<>,这里是代码

public class RestLogin extends AsyncTask<String, String, Boolean> {

private static String URL = "http://Restful webservice here?";
private static final String tag = "Logcat tag: ";

@Override
protected Boolean doInBackground(String... params) {
    //TO DO Auto Generated Method
    return null;
}

现在我被卡住了,如何使用 AsyncTask 调用 Auth() 方法?

提前致谢。

好的,更新:这是新语法

public class RestLogin extends AsyncTask<Void, Void, Void> {

private static String URL = "http://REST Webservice here?";
private static final String tag = "Logcat tag: ";

private String usname, psswrd;
public RestLogin(String username, String password){
    usname = username;
    psswrd = password;
}

protected void onPreExecute(){          
    super.onPreExecute();
} 

protected Void doInBackground(Void... params) {
    Boolean stat = Auth(usname,psswrd);
    return null;
}

protected void onPostExecute(Void result)
  {     
            super.onPostExecute(result);
  } 

public static Boolean Auth(String username,String password)
{
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet request = new HttpGet(URL);
    //adding parameter to request to determine user authentication
    request.addHeader("username",username);
    request.addHeader("password",password);
    //taking handler to get execution status
    ResponseHandler<String> handler = new BasicResponseHandler();
    try
    {
        result = httpclient.execute(request, handler);
    }

        catch (ClientProtocolException cpe)
        {
            cpe.printStackTrace();
        }
        catch (IOException ioe)
        {
            ioe.printStackTrace();
        }
        catch(IllegalArgumentException iae)
        {
            iae.printStackTrace();
        }
        catch(NullPointerException npe)
        {
            npe.printStackTrace();
        }

    httpclient.getConnectionManager().shutdown();
    Log.i(tag,result);
    return Boolean.parseBoolean(result);        
}

}

4

2 回答 2

1

试试这个:

public class RestLogin extends AsyncTask<String, Void, Boolean> {

private static String URL = "http://Restful webservice here?";  
private static final String tag = "Logcat tag: ";

  @Override
  protected Boolean doInBackground(String... params) {

       String username = params[0]; //username
       String password = params[1]; //password

       //now call Auth
       return Auth(username,password);
  }

  @Override
  protected void onPostExecute(Boolean result) {

       super.onPostExecute(result);

       if(result){

            //successful login. Display a Toast or take the user to next screen by using intent.
       }
       else {

           //Display Authentication failed error message.

       }
  }

  public Boolean Auth(String username,String password)
  {

        // your logic.

  }

}

AsyncTask 可以通过以下代码调用。

  new RestLogin().execute(username,password);

如果您需要更多帮助,请告诉我。

于 2013-04-03T13:05:59.467 回答
0

NetworkOnmainthreadException 发生是因为您正在主 UI 线程上运行与网络相关的操作。您应该为此使用Asynctask

当应用程序尝试在其主线程上执行网络操作时引发的异常。

这仅针对面向 Honeycomb SDK 或更高版本的应用程序抛出。允许以早期 SDK 版本为目标的应用程序在其主事件循环线程上进行网络连接,但非常不鼓励这样做。请参阅文档设计响应性。

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

您可以使用 asycntask。http://developer.android.com/reference/android/os/AsyncTask.html

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
            new TheTask(username,password).execute();
      }
class TheTask extends AsyncTask<Void,Void,Void>
{
   String username,pwd;
   public TheTask(String uname, String password)
   {
     username=uname;
     pwd=password;      
   }
  protected void onPreExecute()
  {           super.onPreExecute();
            //display progressdialog.
  } 

   protected void doInBackground(Void ...params)
  {  
        //rest web service. do not update ui here
        boolean somevalue= Auth(username, pwd);
        return null;
  } 

   protected void onPostExecute(Void result)
  {     
            super.onPostExecute(result);
            //dismiss progressdialog.
            //update ui
  } 

 }
于 2013-04-03T12:34:45.623 回答