我是 Android 编程的新手,真的可以在我正在编写的程序中使用一些帮助来建立 Http 连接并显示图像。
我正在使用 Wei-Meng Lee 的“Beginning Android Application Development”一书。代码编译并且没有错误标记但是每次我运行程序时都会出现“错误连接”消息并且没有显示图像。
我查看了 GET 请求的各种代码示例,但找不到适用于我的代码的任何内容。
任何人都可以提供的任何帮助将不胜感激,因为到目前为止我正在努力寻找任何解决方案。
关于使用权限的最后一行代码包含在清单中。
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" />