在另一个相同的请求中创建一个可变的请求

时间:2019-02-28 13:56:43

标签: java rest

我有一个RESTful API,可以像这样进行GET调用

private static String URL_VALUE = "http://completion.amazon.com/search/complete?search-alias=aps&client=amazon-search-ui&mkt=1&q=";


@GetMapping("/estimate")
    public ResponseEntity<Search> search(@RequestParam("keyword") String keyword) {


        keyword = keyword.replace(' ', '+');

        String s = null;

        try {
            s = getJsonData(URL_VALUE + keyword);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!isValidJSON(s)) {
            return ResponseEntity.of(Optional.empty());
        }

        String[] values = processJsonData(s);

        int score = getKeywordScore(values, keyword);


        Search search = new Search();

        search.setKeyword(keyword);
        search.setScore(score);

        return ResponseEntity.of(Optional.ofNullable(search));
    }

getJsonData实际上是向Amazon API发出另一个GET请求

public static String getJsonData(String urlToRead) throws Exception {

        StringBuilder builder = new StringBuilder();

        System.out.println(urlToRead);

        URL url = new URL(urlToRead);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line = "";

        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        reader.close();
        return builder.toString();
    }

我是否应该意识到场景中的任何事情,或者是否有更好的方法来完成任务?我使用cURL来查询我的API

$ curl -X GET http://localhost:8080/estimate?keyword=iphone+charger | jq

谢谢。

0 个答案:

没有答案