1

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;
}
1983
  • 5,322
  • 1
  • 24
  • 38
Nodirbek
  • 460
  • 7
  • 19
  • 1
    possible duplicate of [Using java.net.URLConnection to fire and handle HTTP requests](http://stackoverflow.com/questions/2793150/using-java-net-urlconnection-to-fire-and-handle-http-requests) – BetaRide Jul 22 '15 at 10:22

2 Answers2

1

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());
Thomas Betous
  • 3,215
  • 2
  • 19
  • 39
1

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).

Jebil
  • 946
  • 9
  • 23