我在使用以下代码时遇到严重问题,并会感谢任何形式的帮助。
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;
}
}
答案 0 :(得分:0)
您是否尝试在其他线程中运行代码? 避免使用连接或耗时的任务阻塞主线程。
<强>更新强>
Asynctask示例: