gpt4 book ai didi

java - 如何向另一个域发送请求并在 Spring MVC Controller 中获取响应正文?

转载 作者:行者123 更新时间:2023-11-30 03:20:00 26 4
gpt4 key购买 nike

我有一些 Controller ,我需要将请求发送到另一个域并获取响应结果正文(每次都是html)。我该怎么做? HttpURLConnection 是唯一的解决方案吗?

 @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;
}

最佳答案

以下是发出请求的示例:

    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());

关于java - 如何向另一个域发送请求并在 Spring MVC Controller 中获取响应正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560133/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com