在ResponseEntity中添加http请求

时间:2016-10-14 10:58:27

标签: java http

我是网络服务的初学者,我想在我的ResponseEntity中添加一个http请求,但我认为我做错了。

@RequestMapping(value = "/apiproxy", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity get(HttpServletRequest request, 
        @RequestParam("productName") String productName,
        @RequestParam("version") String version) {

    try {       
        String proxyName = productName.replaceFirst("_product", "") + "_" + version;
        ValidateTransferData result = new ValidateTransferData();
        result.setIsProxy(isProxy);
        result.setIsProduct(isProduct);

    //Get Token
        String url = "http://apibm.fr/token";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return new ResponseEntity<>(result, HttpStatus.OK);            
    }

如何添加我的请求?

非常感谢你。

1 个答案:

答案 0 :(得分:0)

无需将其置于paramas中。只需自动装配它:

@Autowired
private HttpServletRequest request;

@RequestMapping(value = "/apiproxy", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity get(@RequestParam("productName") String productName,
    @RequestParam("version") String version) {

try {       
    String proxyName = productName.replaceFirst("_product", "") + "_" + version;
    ValidateTransferData result = new ValidateTransferData();
    result.setIsProxy(isProxy);
    result.setIsProduct(isProduct);

//Get Token
    String url = "http://apibm.fr/token";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return new ResponseEntity<>(result, HttpStatus.OK);            
}

然后尽可能使用它。