Nodirbek Shamsiev
Nodirbek Shamsiev

Reputation: 552

How do I send a request to another domain and get the response body in a Spring MVC controller?

I have some controller and I need to send request to another domain and get response result body (it is every time html). How can I do it? Is HttpURLConnection only solution?

 @RequestMapping("/")
public ModelAndView mainPage(){
    ModelAndView view = new ModelAndView("main");

    String conten = /*Here is request result to another domain(result is just html, not JSON)*/

    view.addAttribute("statistic","conten);
    return view;
}

Upvotes: 1

Views: 1108

Answers (2)

Jebil
Jebil

Reputation: 1224

For a more simpler way

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(
                new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

Good for reading web-services (JSON Response).

Upvotes: 1

Thomas Betous
Thomas Betous

Reputation: 5123

Here is an exemple to make a request :

    String url = "http://www.google.com/";

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

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

    //add request header
    con.setRequestProperty("User-Agent", USER_AGENT);

    int responseCode = con.getResponseCode();

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

    // Important to be thread-safe
    StringBuffer response = new StringBuffer();

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

    //print html string
    System.out.println(response.toString());

Upvotes: 1

Related Questions