gpt4 book ai didi

Android: Http GET 请求连接失败

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:49 25 4
gpt4 key购买 nike

我是 Android 编程的新手,对于我正在编写的程序建立 Http 连接和显示图像确实需要一些帮助。

我正在使用 Wei-Meng Lee 的“开始 Android 应用程序开发”一书。代码编译并且没有错误标记,但每次我运行程序时都会出现“错误连接”消息并且不显示图像。

我查看了 GET 请求的各种代码示例,但找不到适合我的代码的内容。

任何人都可以提供的任何帮助将不胜感激,因为到目前为止我正在努力寻找任何解决方案。

关于 uses-permission 的最后一行代码包含在 list 中。

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" />

最佳答案

可能是因为 api 版本问题。您必须使用 AsyncTask 类来访问网络功能。

这可能与以下事实有关:在 api 11 及更高版本中,不允许在主线程中访问网络,您可能必须使用 ASYNC 任务。

使用异步任务的例子;

class InternetFileCheack extends AsyncTask<Object, Void, Boolean> {

private Button btn;
private String fileURL;
Context c;

public InternetFileCheack (Button imv, String url, Context ctx) {
this.btn = imv;
this.fileURL = url;
this.c = ctx;
}

@Override
protected Boolean doInBackground(Object... params) {
Boolean sonuc = null;
try {
URL u = new URL(fileURL);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("HEAD");
huc.connect();
int code = huc.getResponseCode();

if (code == HttpURLConnection.HTTP_OK) {
sonuc = true;
} else {
sonuc = false;
}
} catch (Exception e) {
sonuc = false;
}
return sonuc;
}

@Override
protected void onPostExecute(Boolean result) {
btn.setEnabled(result);

if (result) {
Toast.makeText(c, "", Toast.LENGTH_LONG).show();
btn.setVisibility(View.VISIBLE);
} else {
btn.setVisibility(View.GONE);
}
}
}

关于Android: Http GET 请求连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12802260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com