我是Android开发新手,我正在寻找一种方法从互联网下载图片和文字到我的应用程序。我找到了一些教程并将代码包含在我的项目中。当我在模拟器上运行应用程序时,一切正常。如果我在我的设备(三星Galaxy S4)上运行该应用程序,我得到“连接错误”(在HttpDownload.java中),我不知道为什么,因为在其他应用程序中互联网正在工作。
感谢您的帮助。
以下是代码:
HttpDownload.java:
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpDownload extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
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;
}
public Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
public String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0)
{
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return str;
}
}
main_activity:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView meinText;
ImageView meinBild;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meinBild = (ImageView)findViewById(R.id.meinBild);
meinText = (TextView)findViewById(R.id.meinText);
}
public void laden (View view) {
HttpDownload download = new HttpDownload();
meinBild.setImageBitmap(download.DownloadImage("http://www.queness.com/resources/images/png/apple_ex.png"));
}
}
logcat的:
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
04-29 16:36:28.757 32038-32038/com.example.itsme.internetdaten D/OpenGLRenderer﹕ Enabling debug mode 0
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ java.io.IOException: Error connecting
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at com.example.itsme.internetdaten.HttpDownload.OpenHttpConnection(HttpDownload.java:50)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at com.example.itsme.internetdaten.HttpDownload.DownloadImage(HttpDownload.java:60)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at com.example.itsme.internetdaten.MainActivity.laden(MainActivity.java:29)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.view.View$1.onClick(View.java:3964)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.view.View.performClick(View.java:4633)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.view.View$PerformClick.run(View.java:19330)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.os.Looper.loop(Looper.java:157)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5356)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-29 16:36:53.862 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
04-29 16:36:53.882 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
04-29 16:36:53.882 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
04-29 16:36:53.882 32038-32038/com.example.itsme.internetdaten W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
04-29 16:36:53.882 32038-32038/com.example.itsme.internetdaten I/Choreographer﹕ Skipped 61 frames! The application may be doing too much work on its main thread.
清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.itsme.internetdaten" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
答案 0 :(得分:0)
更改:
catch (Exception ex)
{
throw new IOException("Error connecting");
}
到
catch (Exception ex)
{
Log.d("error", ex.toString());
}
并分享发生的确切异常
也可以从互联网上下载图片,您只需使用:
URL url = new URL(address);
Object content = url.getContent();
第三,可能是您可能没有活动的互联网连接,这会引发异常。
答案 1 :(得分:0)
所以问题是网络调用是在Main_Activity(UI活动)中。就像凯已经说的那样,那不再适用了。为什么它在我的模拟器中工作非常简单:他在那里使用Android 2.3。
了解更多信息:
http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html
How to fix android.os.NetworkOnMainThreadException?
我改变了我的代码,一切正常:
Download.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class Download {
public Bitmap downloadBild (String URL) {
Bitmap bild;
try {
bild = new DownloadBildTask().execute(URL).get();
} catch (InterruptedException e) {
bild = null;
} catch (ExecutionException e) {
bild = null;
}
return bild;
}
public String downloadText (String URL) {
String ergebnis;
try {
ergebnis = new DownloadTextTask().execute(URL).get();
} catch (InterruptedException e) {
ergebnis = "Keine Daten";
} catch (ExecutionException e) {
ergebnis = "Keine Daten";
}
return ergebnis;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
InputStream inputStream = downloadInhalt(urls[0]);
String Text = InputStreamToString(inputStream);
inputStream.close();
return Text;
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
}
private class DownloadBildTask extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... urls) {
try {
InputStream inputStream = downloadInhalt(urls[0]);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
return bitmap;
} catch (IOException e) {
return null;
}
}
}
private InputStream downloadInhalt(String myurl) throws IOException {
InputStream is;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
return is;
} catch (Exception e) {
return null;
}
}
private String InputStreamToString(InputStream stream) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
return total.toString();
}
}
Main_Activity
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView meinText;
ImageView meinBild;
Download download = new Download();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meinBild = (ImageView)findViewById(R.id.meinBild);
meinText = (TextView)findViewById(R.id.meinText);
}
public void textLaden(View view) {
String stringUrl = "http://www.openligadb.de/api/getmatchdata/bl1/2014/15";
meinBild.setImageBitmap(null);
meinText.setText(download.downloadText(stringUrl));
}
public void bildLaden(View view) {
String stringUrl = "http://www.queness.com/resources/images/png/apple_ex.png";
meinText.setText("");
meinBild.setImageBitmap(download.downloadBild(stringUrl));
}
}
在清单中:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
为你提供帮助