最终,我的目标是获得一个Android应用程序,从URL接收XML文件,解析它,并显示相关信息(嗯,最终目标比这复杂得多,但这是当前的目标)。我正在使用Wei-Meng Lee的“开始Android应用程序开发”中的示例,我已经注意到本书示例代码中的一些错误(特别是一个错误名称变量,如果Eclipse没有指出它我会错过它完全地)。
然而,目前,该应用程序无法连接到互联网,尽管有权限,有访问权限(3g,4g和wifi都经过测试),并且能够到达机载测试URL浏览器。
以下是相关的代码段。我做错了吗? (注意:我在模拟器和Galaxy S2上测试过)
private InputStream OpenHttpConnection(String urlString)
throws IOException
{
InputStream in = null;
int response = 01;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("Get");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
我尝试过不同的网址,在使用之前检查我是否可以在手机浏览器中连接到每个网址。模拟器也没有任何运气。
更新:使用以下内容的异步代码:
private class BackgroundTask extends AsyncTask
<String, Void, Bitmap> {
protected Bitmap doInBackground(String... url){
// download an image
Bitmap bitmap = DownloadImage(url[0]);
return bitmap;
}
}
protected void onPostExecute(Bitmap bitmap) {
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
上面的方法调用:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackgroundTask().execute("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
}
答案 0 :(得分:1)
您希望将AsyncTask用于需要网络连接的任何内容。您可以按如下方式设置Async :(这会将String作为参数并返回一个InputStream)
public class OpenHttpConnection extends AsyncTask<String, Void, InputStream> {
@Override
protected String doInBackground(String... params) {
String urlstring = params[0];
InputStream in = null;
int response = 01;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("Get");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK){
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}
}
然后你可以像这样调用/运行Async。
OpenHttpConnection connection = new OpenHttpConnection().execute("http://YourURL.com");
InputStream is = connection.get();