Java 使用提供更新JSON对象的web服务
我需要一个学校项目的帮助,我需要连接到提供JSON文档的web服务,每3或4秒更新一次,使用它并使用其中包含的一些信息。JSON如下所示: { 名字:约翰, 姓:史密斯, 伊莎莉:没错, 年龄:25岁, 高度_cm:167.6, 地址:{ 街道地址:第二街21号, 城市:纽约, 州:纽约, 邮政编码:10021-3100 }, 电话:[ { 类型:home,, 电话:212 555-1234, 持续时间:32 }, { 类型:办公室, 电话:646555-4567, 持续时间:79 } ] } Json文件每x秒更新一次,并向文档中添加随机调用, 我需要使用这些信息 我不知道如何连接到这个本地web服务,如何从这个更新文档中检索这些信息,我想使用JAVA,但请告诉我是否有更好的解决方案Java 使用提供更新JSON对象的web服务,java,json,web-services,feed,Java,Json,Web Services,Feed,我需要一个学校项目的帮助,我需要连接到提供JSON文档的web服务,每3或4秒更新一次,使用它并使用其中包含的一些信息。JSON如下所示: { 名字:约翰, 姓:史密斯, 伊莎莉:没错, 年龄:25岁, 高度_cm:167.6, 地址:{ 街道地址:第二街21号, 城市:纽约, 州:纽约, 邮政编码:10021-3100 }, 电话:[ { 类型:home,, 电话:212 555-1234, 持续时间:32 }, { 类型:办公室, 电话:646555-4567, 持续时间:79 } ] }
感谢您提供的所有提示。请参阅此示例,了解如何在Java中通过http从给定url返回JSONObject。这包括对基本身份验证的支持,您可能需要,也可能不需要 您要做的是使用计时器调用此方法以根据需要刷新提要
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Base64;
。。。其他进口
public static JSONObject readJSONFeed(String URL, String username,
String password) throws KeyManagementException,
UnrecoverableKeyException, NoSuchAlgorithmException,
KeyStoreException, ClientProtocolException, IOException {
String auth = username + ":" + password;
HttpClient httpClient = = new DefaultHttpClient;
StringBuilder stringBuilder = new StringBuilder();
// Build HTTP request
HttpPost httpPost = new HttpPost(URL);
httpPost.setHeader(
"Authorization",
"Basic "
+ Base64.encodeToString(auth.getBytes(), Base64.NO_WRAP));
httpPost.setHeader("Accept", "application/json");
// send the request
HttpResponse response = httpClient.execute(httpPost);
// read the result
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else if (statusCode == 401) {
throw new IOException("Authentication failed");
} else {
throw new IOException(statusLine.getStatusCode() + ":"
+ statusLine.getReasonPhrase());
}
// Return the JSON Object
return new JSONObject(stringBuilder.toString());
}
之后,您可以使用JSONObject类的方法(如getIntString或getStringString)检索数据。可以使用getJSONObjectString获取嵌套对象。所有这些都是通过提供字段/对象名称作为参数的字符串来实现的。提供JSON字符串的web服务是否也将JSON字符串推送到web服务?