如何在Android上使用HTTP GET?

时间:2012-04-06 20:34:16

标签: java android http http-get

  

可能重复:
  how do perform Http GET in android?

我想在我的Android应用中使用Google产品/购物API,但我对HTTP GET一无所知。我正在阅读this,它正在为我提供所有这些不同的网址。那么如何在Android中使用带有HTTP GET的Google产品/购物API?

2 个答案:

答案 0 :(得分:1)

首先熟悉HTTP,然后使用URLConnectionApache HttpClient熟悉它。

答案 1 :(得分:1)

以下是我从服务器获取JSON的示例代码。它包括通过HTTP连接到某些东西的基本代码行。

public JSONArray getQuestionsJSONFromUrl(String url, List<NameValuePair> params) {  
    // Making HTTP request
try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        String jsonData = reader.readLine();
        JSONArray jarr = new JSONArray(jsonData);
        is.close();
        return jarr;
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }
    return null;
}