【问题标题】:Android JSON parsing , can't connect to serviceAndroid JSON解析,无法连接到服务
【发布时间】:2012-08-31 07:47:48
【问题描述】:

我正在尝试编写一种方法来调用服务并在 Android 应用程序中取回 JSON 数据。假设所有必要的 gloable 变量都已声明...

这些是我正在使用的库:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

这是我的代码:

public class JSONParser {

String url = "http://gdata.youtube.com/feeds/api/users/eon/uploads?&v=2&max-   results=50&alt=jsonc"; 

JSONObject jObj = null;
JSONArray ja = null;
String json = "";

// constructor
public JSONParser() {

 }



  public JSONObject getJSONFromUrl(String url){
    try {
          URL urlGetter = new URL(url);
        URLConnection tc = urlGetter.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                tc.getInputStream(), "iso-8859-1"), 8);

          StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = in.readLine()) != null) {
            sb.append(line + "\n");
        }


         json = sb.toString();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

      //parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
    return jObj;
   }

它只是不起作用,我尝试在调试模式下运行,当它运行到这一行时:

BufferedReader in = new BufferedReader(new InputStreamReader(
            tc.getInputStream(), "iso-8859-1"), 8);

它抱怨:java.net.UnknownHostException: gdata.youtube.com 我不知道如何解决这个问题......有什么建议吗? 谢谢

顺便说一句,在我的 android 清单中,我已经允许上网:

如果您在浏览器中查找 url,您可以看到 ti 的 json 格式 ...并且可以连接...但是我的代码只是抱怨 unknowhostexception ...."http://gdata.youtube .com/feeds/api/users/eon/uploads?&v=2&max-results=50&alt=jsonc";

【问题讨论】:

  • 您是否通过手机/wifi 连接到互联网?

标签: android json url youtube connection


【解决方案1】:

请将权限放入您的 androidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

【讨论】:

    【解决方案2】:

    我猜您需要使用 urlEncoder.. 对 url 进行编码,因为 url 包含需要替换为 %20..check https://stackoverflow.com/a/3286128/1434631的空间

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多