首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

java,访问一个接口,其后得到接口的返回JSON

2013-11-27 
java,访问一个接口,然后得到接口的返回JSON跪求。。。例子、、、、、HttpClient[解决办法]spring mvc 的话,这样:/*

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();
    }
}

热点排行