2012-07-17 182 views
0

我一直在研究如何通過json發送和接收信息到一個url,最近3天。我發現了很多關於如何去做的文檔和代碼示例,但我無法理解他們在說什麼。我輸入了天知道有多少.jar文件放入我的eclipse包中。有沒有人有一個很好的例子,如何連接到一個URL,發送/接收信息(甚至登錄),解析它,併發送更多的信息?我明白我要求很多。我不需要所有的答案,好的文檔和一些好的例子會讓我很高興。JAVA通過json發送/接收信息

+1

SO不是樣品庫)嘗試使用Google等[此](https://www.google.com/#hl=en&sclient=psy-ab&q=json+java+example&oq=json+java例如+&gs_l = hp.3..0j0i30l3.1588.4478.0.4618.17.13.0.4.4.0.236.2033.0j11j2.13.0 ... 0.0 ... 1c.V4w7MapD_C4&PBX = 1&BAV = on.2,or.r_gc.r_pw.r_cp。 r_qf。,cf.osb&fp = 45f67fe1507830ba&biw = 1366&bih = 614) – 2012-07-17 17:37:12

+0

www.hackerrank.com – 2012-07-17 17:44:06

+0

即時建立一個機器人,我已經建立了膽量,即時通訊只是試圖發送和接收來自該網站...和即時通訊砸我的頭牆壁... – 2012-07-17 17:44:50

回答

3
+0

裏克,感謝您的幫助。在這一點上我不認爲我能理解它。這對我來說都很像希臘人。謝謝你的幫助。 Google GSON圖書館的 – 2012-07-17 18:25:01

+0

+1;我已經在很多項目中使用它來簡化使用JSON的工作。 – 2012-07-17 18:42:32

+1

@TraeMoore - 如果這些庫中的例子看起來像希臘語,那麼我會建議在嘗試像描述的那樣執行一個更大的項目之前,嘗試更加精通Java。你有沒有嘗試製作一個Hello World應用程序?你有對面向對象編程語言的理解嗎?等等... – 2012-07-17 18:44:27

0

發現了一個非常堅實的例子在這裏在這個博客上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); 
    }       
}  
}