如何使用RestTemplate为HTTP GET请求的查询字符串和查询参数构造URL?

时间:2018-09-22 01:09:12

标签: java spring spring-mvc resttemplate

Am使用Java 1.7和Spring 4.0.3 RELEASE

有一个使用URL编码的外部API,其外观与此类似:

 curl -X GET \
      https://api.myservice.com?query_id=1a4445b3e528996d9334b2b8670f786c&variables=%4B%20%0A%09%22property_id%22%63%20%2232144652-414F-4348-4953-455f32373030%22%2C%20%0A%09%22first%22%3A%201%2C%20%0A%09%22publishState%22%3A%20%22PUBLISHED%22%2C%0A%09%22orderByDirection%22%3A%20%22DESC%22%20%0B%7D' \
      -H 'authorization: Bearer dcJhbGciOiJIUzI1NmJ8.eyJ1c2VybmFtZSI6bnVsbCwiZGV2aWNlSWQiOm51bGwsImNsaWVudElkIjoiODJhZUZCTEpJWnMxSG91d3djanVpYlRsUlVuSDlXWTciLCJhZElkIjpudWxsLCJleHAiOjE1Mzc1MjAyOTksImlhdCI6MTUzNzUxNjY5OX0.cdmLbuM6r6pfHiwvDxygVK9aMVx29BTH_AQ3Vyz1maQ

能够像这样在我的Java程序中运行:

private static String encodedUrl = "https://api.myservice.com?query_id=1a4445b3e528996d9334b2b8670f786c&variables=%4B%20%0A%09%22property_id%22%63%20%2232144652-414F-4348-4953-455f32373030%22%2C%20%0A%09%22first%22%3A%201%2C%20%0A%09%22publishState%22%3A%20%22PUBLISHED%22%2C%0A%09%22orderByDirection%22%3A%20%22DESC%22%20%0B%7D";

public static String hitDatastoreWithEncodedUrl(String encodedUrl) {
    String accessToken = OAuth2Client.generateAccessToken();
    String response = null;
    try {
        URL url = new URL(ENCODED_URL);
        HttpsURLConnection connection =(HttpsURLConnection) url.openConnection();
        connection.setRequestMethod("GET");     

        connection.setRequestProperty("Authorization", "Bearer " + accessToken);
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response code: " + connection.getResponseCode());
        System.out.println("Response message: " + connection.getResponseMessage());
            // Read the response:
            BufferedReader reader = new BufferedReader(new InputStreamReader(
            connection.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                logger.info("\n\n\t\tJSON Response: " + line + "\n\n");
                response = line;
            }
            reader.close();
        }
        catch (MalformedURLException mue) {
            logger.error("Problem occurred in ", mue);
        } 
        catch (IOException ioe) {
            logger.error("Problem occurred in ", ioe);          
        }
        return response;
    }

但是,我真的很想使用RestTemplate,这是我尝试过的:

public static HttpEntity<String> hitDatastoreWithEncodedUrl(String encodedUrl) {
    String accessToken = OAuth2Client.generateAccessToken();
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + accessToken);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(encodedUrl)
            .queryParam("query_id", "1a4445b3e528996d9334b2b8670f786c")
            .queryParam("variables", "%4B%20%0A%09%22")
            .queryParam("property_id", "22%63%20%2232144652-414F-4348-4953-455f32373030%22%2C%20%0A%09%22first%22%3A%201%2C%20%0A%09%22publishState%22%3A%20%22PUBLISHED%22%2C%0A%09%22orderByDirection%22%3A%20%22DESC%22%20%0B%7D");


    HttpEntity<?> entity = new HttpEntity<>(headers);

    HttpEntity<String> response = restTemplate.exchange(
            builder.toString(), 
            HttpMethod.GET, 
            entity, 
            String.class);

    return response;
}

收到此错误:

Exception in thread "main" java.lang.IllegalArgumentException: URI is not absolute

似乎query_id是唯一的查询字符串,而: property_id,first,published_state,orderByDirection和DESC是否是每个串联URL的一部分?

我应该如何使用Spring RestTemplate构造此URL?

1 个答案:

答案 0 :(得分:0)

使用builder.toString()代替builder.toUriString()

builder.toString()将返回类似org.springframework.web.util.UriComponentsBuilder@dd3b207的String对象