[英]JAVA send/receive information via json
最近三天,我一直在研究如何通過json向url發送和接收信息。 我已經找到了很多有關如何執行此操作的文檔和代碼示例,但我無法理解他們的意思。 我已經導入了,上帝知道我的Eclipse包中有多少個.jar文件。 有沒有人有一個很好的例子說明如何連接到URL,發送/接收信息(甚至登錄),解析它以及發送更多信息? 我知道我要很多。 我不需要所有的答案,好的文檔和一些好的例子會讓我很高興。
從http://hc.apache.org/開始,然后查看http://code.google.com/p/google-gson/或: http : //wiki.fasterxml.com/JacksonHome
那應該是您所需要的。
在此博客http://www.gnovus.com/blog/programming/making-http-post-request-json-using-apaches-httpclient上找到了一個非常可靠的示例
如果由於某種原因該鏈接不起作用,請粘貼在下面。
public class SimpleHTTPPOSTRequester {
private String apiusername;
private String apipassword;
private String apiURL;
public SimpleHTTPPOSTRequester(String apiusername, String apipassword, String apiURL) {
this.apiURL = apiURL;
this.apiusername = apiusername;
this.apipassword = apipassword;
}
public void makeHTTPPOSTRequest() {
try {
HttpClient c = new DefaultHttpClient();
HttpPost p = new HttpPost(this.apiURL);
p.setEntity(new StringEntity("{\"username\":\"" + this.apiusername + "\",\"password\":\"" + this.apipassword + "\"}",
ContentType.create("application/json")));
HttpResponse r = c.execute(p);
BufferedReader rd = new BufferedReader(new InputStreamReader(r.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
//Parse our JSON response
JSONParser j = new JSONParser();
JSONObject o = (JSONObject)j.parse(line);
Map response = (Map)o.get("response");
System.out.println(response.get("somevalue"));
}
}
catch(ParseException e) {
System.out.println(e);
}
catch(IOException e) {
System.out.println(e);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.