java请求URL返回JSON

需求:

  • testCase 访问本地的 url,获得返回 url 的 json 数据

1,url 路径 比如访问 http://localhost:8080/spb/result

Controller如下

@RestController
@RequestMapping("/spb")
public class JsonController extends MainController {

    private static final Logger logger = LoggerFactory.getLogger(JsonController.class);

    @RequestMapping("/result")
    public String resultJson() {
        return "{\"name\": \"小明\",\"age\": 14,\"gender\": true,\"height\": 1.65,\"grade\": null,\"middle-school\": \"\\\"W3C\\\" Middle School\",\"skills\": [\"JavaScript\",\"Java\",\"Python\",\"Lisp\"]}";
    }

运行项目访问url如下

那我们在testCase中如何访问这个url路径来获取json数据呢?如下

 

    @Test
    public void testJsonResult() throws IOException {
        URL connect = isConnect("http://localhost:8080/spb/result");
        if (null != connect){
            String json = loadJson(connect.toString());
            System.out.println(json);
        }
    }


    public synchronized URL isConnect(String urlStr) {
        URL url = null;
        HttpURLConnection connection = null;
        int counts = 0;
        if (urlStr == null || urlStr.length() <= 0) {
            return null;
        }
        while (counts < 5) {
            try {
                url = new URL(urlStr);
                connection = (HttpURLConnection) url.openConnection();
                int code = connection.getResponseCode();
                System.out.println(counts +" = "+code);
                if (code == 200) {
                    System.out.println("URL可用!");
                }
                break;
            } catch (Exception ex) {
                counts++;
                System.out.println("URL不可用,连接第 " + counts +"次");
                urlStr = null;
                continue;
            }
        }
        return url;
    }


    public static String loadJson(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            // 设置为utf-8的编码 才不会中文乱码
            BufferedReader in = new BufferedReader(new InputStreamReader(uc
                .getInputStream(), "utf-8"));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json.toString();
    }

运行效果为

 

易错点注意

  • 在运行testCase之前需要确认服务器是否启动(tomcat是否启动),如果没有启动获取不到json数据
  • 如果连接不上url,请确认访问的端口是否与你tomcat的端口相同

 

 

你可能感兴趣的:(JSON,java基础)