Java 如何将请求发送到另一个域并在SpringMVC控制器中获取响应主体?
我有一些控制器,我需要将请求发送到另一个域并获得响应结果体(每次都是html)。我怎么做?HttpURLConnection是唯一的解决方案吗Java 如何将请求发送到另一个域并在SpringMVC控制器中获取响应主体?,java,spring,spring-mvc,Java,Spring,Spring Mvc,我有一些控制器,我需要将请求发送到另一个域并获得响应结果体(每次都是html)。我怎么做?HttpURLConnection是唯一的解决方案吗 @RequestMapping("/") public ModelAndView mainPage(){ ModelAndView view = new ModelAndView("main"); String conten = /*Here is request result to another domain(result is
@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());
为了更简单的方法
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();
}
}
非常适合阅读web服务(JSON响应)。可能重复的