Ответ 1
Вы должны получить ошибку компиляции.
Это правильная версия:
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("https://www.googleapis.com/shopping/search/v1/public/products/?key={my_key}&country=&q=t-shirts&alt=json&rankByrelevancy="));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
Поэтому теперь, если у вас есть ошибка, ваш ответ будет возвращен как null.
После того, как вы ответили и проверили его на нуль, вы захотите получить контент (т.е. ваш JSON).
http://developer.android.com/reference/org/apache/http/HttpResponse.html http://developer.android.com/reference/org/apache/http/HttpEntity.html http://developer.android.com/reference/java/io/InputStream.html
response.getEntity().getContent();
Это дает вам InputStream для работы. Если вы хотите преобразовать это в строку, вы должны сделать следующее или эквивалентное:
http://www.mkyong.com/java/how-to-convert-inputstream-to-string-in-java/
public static String convertStreamToString(InputStream inputStream) throws IOException {
if (inputStream != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
inputStream.close();
}
return writer.toString();
} else {
return "";
}
}
Когда у вас есть эта строка, вам нужно создать JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html
JSONObject json = new JSONObject(inputStreamAsString);
Готово!