得到JSON响应在Android中的HTTP查询
问题描述:
我想获得BING结果到JSON形式的查询,然后使其JSON对象和执行一些事情。得到JSON响应在Android中的HTTP查询
但我不能接收响应:(
我尝试以下两种方法
任何人可以帮助我解决问题
Approach1:?
URL searhURL;
//String imageurl = "http://api.bing.net/json.aspx?AppID="+myBingAppID+"&Query="+formattedQuery+"&Sources=images";
String imageurl="http://www.bing.com/images/search?q="+formattedQuery+"&go=&qs=n&form=QBLH&filt=all";
URL url = new URL(imageurl);
InputStream is = null;
URLConnection connection = url.openConnection();
Log.d(LOGGER, "1.0");
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream())); //problem is here
Log.d(LOGGER, "2.0");
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.d(LOGGER, "3.0");
jSONString = builder.toString();
//after cutting off the junk, its ok
Log.d(LOGGER, "String is : "+jSONString);
JSONObject jSONObject = new JSONObject(jSONString); //whole json object
正如你所看到的,我尝试了使用API密钥和不使用API密钥。但是仍然有问题在线评论为问题在这里。
方法2
String jsonString="";
try {
URL url = new URL(imageurl);
Log.d(LOGGER, "1");
BufferedReader in = new BufferedReader(new InputStreamReader(
url.openStream())); //problem here
Log.d(LOGGER, "2");
String inputLine;
while ((inputLine = in.readLine()) != null) {
//JSON data get stored as a string
jsonString = inputLine;
}
Log.d(LOGGER, "3");
in.close();
Log.d(LOGGER, "String is : "+jsonString);
}
catch (IOException e) {
e.printStackTrace();
}
答
这就是为什么我们建议您始终包括logcat的输出,因为没有办法,我们可以计算出来离不开它。
添加到您的AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
你得到你所使用的网络SecurityException
,因为你还没有告诉Android系统。
+0
非常感谢!这帮助了我:)我绝对忘了添加这个权限。 – adityag 2012-02-12 05:47:21
+1
不客气,祝你好运。 – 2012-02-12 13:06:35
什么问题? – 2012-02-11 18:57:21
超出缓冲区读取器的日志语句不会显示在log cat中。而且jsonString没有被制作/显示 – adityag 2012-02-11 19:04:38
http://justpaste.it/qf4是确切的log cat语句。 – adityag 2012-02-11 21:28:37