android - 使用 HttpGet 获取网页信息不起作用
问题描述
嗨,我对 android 开发非常陌生,目前正在开发我的第一个 android 应用程序项目。我想将 Web 内容加载到应用程序并将内容存储为字符串。我尝试使用 AsyncTask 进行 httpGet,但布尔 doInBackground 函数总是返回 false。我找不到原因。有人可以帮我吗?谢谢!
public class MainActivity extends Activity {
public EditText url_text;
public TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//url_text = (EditText) findViewById(R.id.address);
//textView = (TextView) findViewById(R.id.tv);
final String url = "http://www.google.com/";
new JSONAsyncTask().execute(url);
}
public class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
public String resultString = "";
@Override
protected Boolean doInBackground(String... params) {
String url = params[0];
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
resultString = data;
return true;
}
} catch (Exception e) {
System.out.println("Some error occured.");
}
return false;
}
@Override
protected void onPostExecute(Boolean result){
Log.d("TAG", resultString);
}
}
}
解决方案
推荐阅读
- javascript - 用户登录时更新所有用户相关数据(可观察)
- django - Django ORM。使用 AND 子句过滤多对多
- javascript - 在meteor.js的源代码中调试
- c# - EF 核心关系
- java - Java随机数生成器生成相同的数字但是当我比较它们时它不一样
- javascript - $ {I} 和 ${colours[i]} 不在控制台中打印值?
- php - 如何在 Windows 上使用 nginx 从 XHR 到 Laravel 代理文件上传与 multipart/form-data?
- python - 如何浏览动态分配其内容的 Microsoft CVE 网页(最好使用 Python)?
- r - 如何在ggplot2图例中包含黄土线?
- php - 如何在图像字符串中添加换行符(
)(PHP中的文本到图像)