java,访问一个接口,然后得到接口的返回JSON
跪求。。。例子、、、、、
HttpClient
分享到:
——解决方案——————–
spring mvc 的话,这样:
/**
* 测试返回JSON数据
* @param session
* @return
*/
@RequestMapping(value=”/test”)
@ResponseBody
public Object test(HttpSession session){
return session.getAttribute(“permit”);
}
——解决方案——————–
一个简略的例子:
package com.ljn.base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* @author lijinnan
* @date:2013-11-11 下午6:12:26
*/
public class HttpJSONTest {
/**
* @param args
*/
public static void main(String[] args) {
String url = “http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo”;
String json = loadJSON(url);
System.out.println(json);
}
public static String loadJSON (String url) {
StringBuilder json = new StringBuilder();
try {
URL oracle = new URL(url);
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return json.toString();
}
}