Android/Java:JSON HTTP 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5933839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android/Java: JSON HTTP Request
提问by mergesort
How can I make a request to get/download http://coolsite.com/coolstuff.jsonin Java/Android
如何在 Java/Android 中请求获取/下载http://coolsite.com/coolstuff.json
回答by Tony the Pony
Android supports all the standard java.net
classes. The simplest way to retrieve content via HTTP is to call openStream()
on your URL and read it:
Android 支持所有标准java.net
类。通过 HTTP 检索内容的最简单方法是调用openStream()
您的 URL 并读取它:
URL url = new URL("http://coolsite.com/coolstuff.js"); InputStream in = url.openStream(); InputStreamReader reader = new InputStreamReader(in); // read the JSON data
There are libraries for reading JSON in Java (see http://json.org/java), but since the format is really simple, you can parse it easily.
有一些用于在 Java 中读取 JSON 的库(请参阅http://json.org/java),但由于格式非常简单,因此您可以轻松解析它。
回答by LocalPCGuy
From a cached copy of:
从缓存的副本:
How-to: Android as a RESTful Client
This is a how-to focused on creating a RESTful java object at Android. I've used HTTPClient, HTTPEntry, HTTPGet, HTTPResponse, JSONArray and JSONObject classes. I think it'll be useful if we need to use a web-service from client application.
这是一个专注于在 Android 上创建 RESTful java 对象的方法。我使用过 HTTPClient、HTTPEntry、HTTPGet、HTTPResponse、JSONArray 和 JSONObject 类。我认为如果我们需要使用来自客户端应用程序的 Web 服务会很有用。
I've implemented a simple Java Object called RestClient which connects to a given Rest-JSON service. After connection, this object prints response content. Using this content, a JSONObject created. Then, RestClient prints the JSONObject's content, parses all values of this object and prints them as well. And as a last job, RestClient pushes a sample value to the JSONObject.
我已经实现了一个名为 RestClient 的简单 Java 对象,它连接到给定的 Rest-JSON 服务。连接后,该对象打印响应内容。使用此内容,创建了一个 JSONObject。然后,RestClient 打印 JSONObject 的内容,解析该对象的所有值并打印它们。作为最后一项工作,RestClient 将示例值推送到 JSONObject。
I've uploaded RestClient. Hope it'll be useful.
我已经上传了 RestClient。希望它会很有用。
P.s: To get access to internet at Android, following field must be included to AndroidManifest.xml file of the project.
Ps:要在Android上访问互联网,项目的AndroidManifest.xml文件中必须包含以下字段。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
RestClient code:
休息客户端代码:
package praeda.muzikmekan;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class RestClient {
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/* This is a test function which will connects to a given
* rest service and prints it's response to Android Log with
* labels "Praeda".
*/
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
Log.i("Praeda",result);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
// A Simple JSONObject Parsing
JSONArray nameArray=json.names();
JSONArray valArray=json.toJSONArray(nameArray);
for(int i=0;i<valArray.length();i++)
{
Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
+"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
}
// A Simple JSONObject Value Pushing
json.put("sample key", "sample value");
Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}