【问题标题】:Android - download JSON file from urlAndroid - 从 url 下载 JSON 文件
【发布时间】:2011-02-17 09:58:43
【问题描述】:

是否可以从 URL 下载包含 JSON 数据的文件?此外,我需要获取的文件没有文件扩展名,这是一个问题还是我可以在下载时强制它具有 .txt 扩展名?

更新: 我忘了提到,该网站需要输入用户名和密码才能访问我知道的网站。有没有办法在我检索文件时输入这些值?

【问题讨论】:

  • 嗨,试试this

标签: java android json file url


【解决方案1】:

您尝试过使用 URLConnection 吗?

private InputStream getStream(String url) {
    try {
        URL url = new URL(url);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(1000);
        return urlConnection.getInputStream();
    } catch (Exception ex) {
        return null;
    }
}

还记得像这样编码你的参数:

String action="blabla";
InputStream myStream=getStream("http://www.myweb.com/action.php?action="+URLEncoder.encode(action));

【讨论】:

  • 别忘了关闭输入流 :)
【解决方案2】:

当然。就像其他人指出的那样,基本 URL 是一个足够好的起点。

虽然其他代码示例有效,但 JSON 内容的实际访问可以是单行的。使用Jackson JSON 库,您可以:

Response resp = new ObjectMapper().readValue(new URL("http://dot.com/api/?customerId=1234").openStream(),Response.class);

如果您想将 JSON 数据绑定到您定义的“响应”中:获取地图,您可以这样做:

Map<String,Object> map = new ObjectMapper().readValue(new URL("http://dot.com/api/?customerId=1234").openStream(), Map.class);

关于添加用户信息;这些通常使用Basic Auth 传递,其中您将base64 编码的用户信息作为“授权”标头传递。 为此,您需要从 URL 打开 HttpURLConnection,并添加标题; JSON访问部分还是一样的。

【讨论】:

    【解决方案3】:

    基本上你会做这样的事情:

    代码:

    URL address = URL.parse("http://yoururlhere.com/yourfile.txt"); 
    URLConnection conn = new URLConnection(address);
    InputStream is = conn.getInputStream(); 
    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer bab = new ByteArrayBuffer(64); 
    int current = 0;
    
    while((current = bis.read()) != -1) {
      bab.append((byte)current); 
    }
    
    FileOutputStream fos = new FileOutputStream(new File(filepath));
    fos.write(bab.toByteArray());
    fos.close();
    

    【讨论】:

    • 这将失败,因为您无法实例化 URLConnection。
    【解决方案4】:

    Here 是我编写的一个类文件和一个接口,用于从 URL 下载 JSON 数据。至于用户名密码认证,这将取决于它在您访问的网站上的实现方式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      相关资源
      最近更新 更多