我是Android新手,我真的可以用一些帮助来编写一个程序来建立一个Http连接并显示一个图像。Android:Http GET请求无法连接
我正在使用Wei-Meng Lee的'Beginning Android Application Development'一书。代码编译并且没有错误标记,但是每次运行程序时都会出现“错误连接”消息,并且不会显示图像。
我已经看过GET请求代码的各种示例,但找不到任何适用于我的代码的代码。
任何人都可以提供的帮助将不胜感激,因为我目前正在努力看到任何解决方案。
关于使用权限的最后一行代码包含在Manifest中。
ImageView image;
private InputStream OpenHttpConnection(String urlString)
throws IOException {
InputStream in = null;
int response = -1;
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 Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
catch (IOException e1) {
Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
return bitmap;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_network);
Bitmap bitmap = DownloadImage("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bitmap);
}
<uses-permission
android:name="android.permission.INTERNET" />
错误信息究竟是什么? – waqaslam
确实。请看看你正在捕获的异常,并告诉我们它说了什么(例如'Log.e(“LOGNAME”,“Exception caught。”,ex);') –
错误消息是“Error Connecting “我在GET请求之后写入了代码。每次我运行程序时,都会显示图像而不是显示图像。 Amourreux设法通过使用ASYNC而不是我的代码来解决这个问题。感谢无论如何,看看这个问题,非常感谢。 – AndrewLugs