2014-07-24 35 views
-2

我们有一个通过HTTP通过API的应用程序。 如果我想从从Linux脚本这个API获取数据,我只是运行像访问来自java的http API

curl -s http://10.20.1.116:8080/afa/report?session=fd58603c6673 

,并取回JSON

{ 
    "content" : [ { 
    "id" : 6243, 
    "user" : "admin", 
    "firewall" : "NewGroup_Lab", 
    "updateDate" : 1406225284152, 
    "attributes" : { 
     "EmailNotification" : "True", 
     "Job_status" : "COMPLETED", 
     "Submitted_by" : "afa", 
     "Regulatory_score_glba_group" : "22,9,10,65", 
     "Pid" : "11254", 
     "Owner" : "admin", 
     "Regulatory_score_nist_800-41_group" : "15,13,8,52", 
    } 

现在,我们要使用Java程序这个API。访问API URL的正确方式是什么?我应该用什么来取代卷曲?

谢谢。


更新。

我想通了。我觉得这很容易。 我需要这个将输出传递给jackson进一步解析。 看起来像杰克逊本身可以访问的URL没有任何额外的代码。

public Map jsonToMap(){ 
    URL url = new URL("10.20.1.116:8080/afa/report?session=fd58603c6673"); 
    ObjectMapper mapper = new ObjectMapper(); 
    return mapper.readValue(url, Map.class); 
} 

谢谢大家的帮助。

+0

可能重复的[如何在java中发送HTTP请求?](http://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java) –

回答

-1
URL url = new URL("your_url"); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
String str; 
// read a line 
while ((str = in.readLine()) != null) { 
    //write to file, concatenate to string, etc 
} 
+0

请尝试包含一个解释在你的回答中,而不仅仅是代码。 –

+0

这段代码不言自明 – sunrize920

+0

提问者似乎是新手,对他们来说可能不是自我解释。 –

-1

你会想看看无论是内置在Java中HttpURLConnection类或具有更好的API的Apache HttpComponents库。

HttpURLConnection非常冗长。

你的榜样与Apache HttpComponents:

String json = Request.Get("http://10.20.1.116:8080/afa/report?session=fd58603c6673") 
    .connectTimeout(1000) 
    .socketTimeout(1000) 
    .execute() 
    .returnContent() 
    .asString(); 

here对于如何使用HttpURLConnection的一个伟大的答案。 Here是Apache HttpComponents中的HttpClient API的一个示例。

+0

好吧,如果你因为生气而没有降低一个好的答案,我会收回downvote。 Stackoverflow是为了帮助人们。根据http://stackoverflow.com/help/how-to-answer,不好的答案(又名链接只是答案)应该被低估,因为它们不是很好的答案。如果您不希望您的答案被误认为是错误的答案,请不要提交答案直至答案完整 – sunrize920