0

我面临以下代码的严重问题,并会感谢任何形式的帮助。

public class WebHandler
{
private String username;
private String password;
private boolean errorOccured;
private String errorMessage;
private String server;

public WebHandler(String server)
{
    this.server = server;
    StrictMode.ThreadPolicy policy = new   
            StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

public void setUsername(String username)
{
    this.username = username;
}

public void setPassword(String password)
{
    this.password = password;
}

public String getInternetData(String url)
{
    BufferedReader bufferedReader = null;
    String data = null;

    try
    {
        HttpClient client = new DefaultHttpClient();
        URI website = new URI("http://google.com"); 
        HttpGet request = new HttpGet();
        request.setURI(website);
        HttpResponse response = client.execute(request);
        bufferedReader = new BufferedReader(new    
                    InputStreamReader(response.getEntity().getContent()));

        StringBuffer stringBuffer = new StringBuffer("");

        String line;

        while ((line = bufferedReader.readLine()) != null)
        {
            stringBuffer.append(line);
            Log.e("PLW", line);
        }

        bufferedReader.close();
        data = stringBuffer.toString();
    } 
    catch(Exception e)
    {
        this.errorOccured = true;
        this.errorMessage = e.getMessage();
    }

    return data;

}

public String Post(List<NameValuePair> nameValuePair, String url)
{
    String result = null;

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://www.google.com/");

    nameValuePair.add(new BasicNameValuePair("usernmae", this.username));
    nameValuePair.add(new BasicNameValuePair("password", this.password));

    Log.e("PLW_0", "called post..." );

    try
    {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        HttpResponse response = httpClient.execute(httpPost);
        result = response.toString();
        Log.e("PLW_1", "response:" + result);
    } 
    catch (Exception e)
    {
        // writing exception to log
        Log.e("PLW_2", "Error:", e);
        Log.e("PLW_3", "error:" + e.getMessage());
    }
    return result;
}

public boolean hasError()
{
    return this.errorOccured;
}

public String getError()
{
    return this.errorMessage;
}
}
4

1 回答 1

0

您是否尝试在其他线程中运行您的代码?避免使用连接或耗时的任务阻塞主线程。

更新:

异步任务示例:

  1. http://anujarosha.wordpress.com/2012/01/27/handling-http-post-method-in-android/
  2. http://pcfandroid.wordpress.com/2011/07/14/http-post-with-asynctask-android-tutorial/
于 2013-02-03T23:56:48.883 回答