gpt4 book ai didi

android - 在 Android 上从 URL 检索 JSON

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:41 26 4
gpt4 key购买 nike

我的手机APP以文本方式完美下载内容。下面是执行此操作的代码。我调用 Communicator 类和 exectueHttpGet:

URL_Data = new Communicator().executeHttpGet("Some URL");

public class Communicator {
public String executeHttpGet(String URL) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "text/plain; charset=utf-8");
request.setURI(new URI(URL));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

StringBuffer sb = new StringBuffer("");
String line = "";

String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String page = sb.toString();
//System.out.println(page);
return page;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
Log.d("BBB", e.toString());
}
}
}
}
}

我收到的是这个(URL 的源代码):

[{"id_country":"3","country":"AAA"},{"id_country":"8","country":"BBB"},
{"id_country":"66","country":"CCC"},{"id_country":"14","country":"DDD"},
{"id_country":"16","country":"EEE"},{"id_country":"19","country":"FFF"},
{"id_country":"24","country":"GGG"},{"id_country":"33","country":"HHH"},
{"id_country":"39","country":"III"},{"id_country":"44","country":"JJJ"},
{"id_country":"45","country":"KKK"},{"id_country":"51","country":"LLL"},
{"id_country":"54","country":"MMM"},{"id_country":"55","country":"NNN"},
{"id_country":"57","country":"OOO"},{"id_country":"58","country":"PPP"},
{"id_country":"63","country":"RRR"},{"id_country":"65","country":"SSS"}]

此响应是一个字符串。在服务器上它作为 JSON 对象输出(使用 PHP),现在在我的 Android PHP 中我想将这个字符串转换为 JSON。这可能吗?

最佳答案

您收到的是来自 InputStream 的一系列字符,您将其附加到 StringBuffer 并在最后转换为 String - 所以String 的结果没问题 :)

你想要的是通过 org.json.* 类对这个字符串进行后处理

String page = new Communicator().executeHttpGet("Some URL");
JSONObject jsonObject = new JSONObject(page);

然后处理 jsonObject。由于您收到的数据是一个数组,您实际上可以说

String page = new Communicator().executeHttpGet("Some URL");
JSONArray jsonArray = new JSONArray(page);
for (int i = 0 ; i < jsonArray.length(); i++ ) {
JSONObject entry = jsonArray.get(i);
// now get the data from each entry
}

关于android - 在 Android 上从 URL 检索 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5577857/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com