我正在尝试使用简单的 HTTP get 从网页加载字符串。但是,当我在模拟器中运行应用程序时,我遇到了严格的策略违规,并且没有显示任何内容。策略违规被列为“策略=31 违规=4”。如果我将 permitNetwork() 添加到 ThreadPolicy 初始化中,LogCat 会告诉我 google.com 无法解析为地址。显然,我遗漏了一些东西,但我的印象是这就是我应该如何处理网络操作。
编辑:我已经改变了我的 HttpExampleActivity.java,我现在有了这个:
package com.android.httpexample;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.StrictMode.ThreadPolicy.Builder;
import android.widget.TextView;
public class HttpExampleActivity extends Activity {
TextView httpStuff;
@Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new Builder().detectAll().penaltyLog().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new Runnable() {
public void run() {
httpStuff = (TextView) findViewById(R.id.tvHttp);
httpStuff.post(new Runnable(){
public void run(){
GetProcedure test = new GetProcedure();
String returned;
try{
returned = test.getInternetData();
httpStuff.setText(returned);
} catch(Exception e){
e.printStackTrace();
}
}
});
}
}).start();
}
}
在我的 GetProcedure.java 中,我有这个:
package com.android.httpexample;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class GetProcedure {
public String getInternetData() throws Exception {
BufferedReader in = 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);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) != null)
{
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if(in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}