我是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