我一直在研究一个Android项目,我想要一些API来获取信息。看起来这应该是非常基本的!
以下是我的代码的一般要点:
private InputStream retrieveStream2(String url)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
System.out.println("getRequest == " + getRequest);
try {
HttpResponse getResponse = client.execute(getRequest);//here is teh problem
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (Exception e)
{
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL, YO " + url, e);
}
return null;
}
其中url变量是字符串“http://search.twitter.com/search.json?q=javacodegeeks”。
正如您所看到的,该网站上有一些不错的JSON信息;我的问题是,每次调用'client.execute(getRequest);''时,程序都会抛出并捕获异常。没有用!
我听说过两件事:
1)您必须为模拟器/设备设置使用互联网的权限! - 我想我已经覆盖了这个,但也许我做错了! 在androidmanifest.xml中我添加了
< uses-permission android:name="android.permission.INTERNET" >< /uses-permission>
所以就是这样。
2)(我不太确定)你不能在'ui'线程中启动'网络'线程。我不完全确定这意味着什么,但我继续前进并遵循Android Threads,Handlers和AsyncTasks的一些教程。这里:请查看我遵循的AsyncTask教程下的代码:
http://www.vogella.de/articles/AndroidPerformance/article.html
在跟随AsyncTask教程之后,我发现我仍然遇到了同样的问题 -
行: HttpGet httpGet = new HttpGet(url) 总是像以前一样抛出异常。
以下是我尝试上面的线程教程的logcat:
02-27 20:43:28.565: I/ActivityManager(92): START {cmp=com.Prometheus.R1/.JsonParsingActivity} from pid 574
02-27 20:43:28.565: W/WindowManager(92): Failure taking screenshot for (180x300) to layer 21010
02-27 20:43:28.896: I/System.out(574): pre execute
02-27 20:43:29.236: I/ActivityManager(92): Displayed com.Prometheus.R1/.JsonParsingActivity: +638ms
02-27 20:43:29.329: I/ARMAssembler(35): generated scanline__00000077:03010104_00008001_00000000 [ 89 ipp] (110 ins) at [0x40fad6a8:0x40fad860] in 7204915 ns
02-27 20:43:30.016: W/System.err(574): java.net.UnknownHostException: Unable to resolve host "search.twitter.com": No address associated with hostname
02-27 20:43:30.016: W/System.err(574): at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
02-27 20:43:30.026: W/System.err(574): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
02-27 20:43:30.026: W/System.err(574): at java.net.InetAddress.getAllByName(InetAddress.java:220)
02-27 20:43:30.026: W/System.err(574): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
02-27 20:43:30.036: W/System.err(574): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-27 20:43:30.036: W/System.err(574): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-27 20:43:30.046: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-27 20:43:30.055: W/System.err(574): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-27 20:43:30.055: W/System.err(574): at com.Prometheus.R1.JsonParsingActivity$DownloadWebPageTask.doInBackground(JsonParsingActivity.java:88)
02-27 20:43:30.055: W/System.err(574): at com.Prometheus.R1.JsonParsingActivity$DownloadWebPageTask.doInBackground(JsonParsingActivity.java:1)
02-27 20:43:30.055: W/System.err(574): at android.os.AsyncTask$2.call(AsyncTask.java:264)<br/>
02-27 20:43:30.066: W/System.err(574): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
02-27 20:43:30.066: W/System.err(574): at java.util.concurrent.FutureTask.run(FutureTask.java:137)<br/>
02-27 20:43:30.066: W/System.err(574): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
02-27 20:43:30.076: W/System.err(574): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
02-27 20:43:30.076: W/System.err(574): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
02-27 20:43:30.087: W/System.err(574): at java.lang.Thread.run(Thread.java:856)
02-27 20:43:30.108: W/System.err(574): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
02-27 20:43:30.116: W/System.err(574): at libcore.io.Posix.getaddrinfo(Native Method)
02-27 20:43:30.116: W/System.err(574): at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
02-27 20:43:30.126: W/System.err(574): at java.net.InetAddress.lookupHostByName(InetAddress.java:411)
02-27 20:43:30.126: W/System.err(574): ... 18 more
02-27 20:43:30.136: I/System.out(574): Except thrown by url http://search.twitter.com/search.json?q=javacodegeeks, ....
02-27 20:43:30.136: I/System.out(574): response =
您可以看到异常是UnknownHostException:
“ava.net.UnknownHostException:无法解析主机”search.twitter.com“:没有与主机名关联的地址”
但我不认为该网站是不可接受的......
任何人都可以告诉我发生了什么以及我需要做些什么才能通过它?
答案 0 :(得分:13)
检查清单的权限,确保添加了以下内容:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
答案 1 :(得分:10)
想出来。显然我把AVD从“飞机模式”上移开了。
对于遇到与我相同问题的人,你可能正在使用无线技术。出于某种原因,andriod会查看您的LAN卡,因此请转到您的网络连接并右键单击LAN卡 - 禁用该功能!问题解决了。
答案 2 :(得分:1)
我认为问题在于您在http请求或互联网连接中提供的网址,请查看以下链接,它会对您有所帮助Link
答案 3 :(得分:1)
我也遇到了这个问题。在我的情况下,我使用HttpURLConnection来加载JSON。当我启用&#34;跟随重定向时,问题得到解决。&#34;这是一个有效的代码片段:
HttpURLConnection connection = null;
BufferedReader reader = null;
String JSON_data = null;
try {
final int half_hour = 30 * 60;
URL fetch = new URL(requestUrl);
connection = (HttpURLConnection) fetch.openConnection();
// FIXED: request to follow redirects - this seems to solve networking issues on older devices < API 21
connection.setInstanceFollowRedirects(true);
connection.setUseCaches(true);
connection.setDefaultUseCaches(true);
connection.setRequestMethod("GET");
connection.addRequestProperty("Cache-Control", "max-age="+half_hour);
connection.addRequestProperty("X-Auth-Token", getString(R.string.api_key));
boolean redirect = false;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
Log.d(TAG, "===> HTTP STATUS CODE: " + status + ", redirect=" + redirect);
connection.connect();
// Read the input stream into a String
InputStream inputStream = connection.getInputStream();
if (inputStream == null) {
return;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n");
}
if (buffer.length() == 0) {
return;
}
JSON_data = buffer.toString();
Log.d(TAG, "JSON_data=" + JSON_data);
} catch (Exception e) {
// possible UnknownHostException on older Android device?
Log.e(TAG, "HttpURLConnection Exception - e=" + e.getMessage());
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.e(TAG, "Error closing stream - e=" + e.getMessage());
}
}
}
答案 4 :(得分:0)
这并不意味着您对应用程序有疑问,这是因为您使用的是Wi-Fi互联网, 因此,要解决此问题,请使您的笔记本电脑保持Wi-Fi连接并重新启动模拟器
对我有用
答案 5 :(得分:0)
就我而言,我刚刚重新启动了包含模拟器的Android Studio,并且该软件没有错误。
答案 6 :(得分:0)
有时候,我在分析系统中看到类似的日志。我认为服务器中存在问题。有时它没有响应(短时间)。或者,也许是用户连接较弱(例如,在地下或建筑物内部)。
答案 7 :(得分:-3)
您可以通过以下代码段在主线程中允许网络访问。在您的活动的onCreate()方法的开头。
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);