如何从Android中的任何URL获取响应,而不是在响应后我想解析它

sam*_*m_k 1 android

我想知道json如何工作以及我们如何获得响应表单url然后我想解析这个响应.

Rej*_*eri 7

了解json阅读此链接..

http://secretgeek.net/json_3mins.asp

你可以在android上找到"json tutorials"

您要做的第一件事就是获取响应文本.

private String getResponseText(String stringUrl) throws IOException
{
    StringBuilder response  = new StringBuilder();

    URL url = new URL(stringUrl);
    HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
    if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
    {
        BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
        String strLine = null;
        while ((strLine = input.readLine()) != null)
        {
            response.append(strLine);
        }
        input.close();
    }
    return response.toString();
}
Run Code Online (Sandbox Code Playgroud)

在此之后,您将获取响应文本并将其解析为json根对象,如此

String responseText = GetResponseText(requestUrl);
JSONObject mainResponseObject = new JSONObject(responseText);
Run Code Online (Sandbox Code Playgroud)

然后根据数据的结构,使用以下类解析JSONObject:JSONObject JSONArray

并使用在类上定义的get方法获取值,在文档中检查它们.

http://developer.android.com/reference/org/json/JSONObject.html

网上有很多例子可以搜索它们..