httpclient请求链接返回html或者javascript并返回给浏览器

一般调对方接口, 对方返回给你的可能是json或者xml数据亦或是流。但是我们同时也会遇到这么一些情况,对方返回给你的可能是html页面代码,也有可能是一段js代码,这个时候controller该如何返回给前端呢?

应用场景:

1、前端调对方接口需要转化为后台调对方接口的方式

2、后台调对方接口返回的就是页面或者js源码

一般最好的解决办法是: 可利用jsoup直接将页面打印到前端,废话不多说了,先上代码:

1.maven 引入httpclient 和 jsoup的jar包



	org.apache.httpcomponents
	httpclient
	4.5.2


	org.jsoup
	jsoup
	1.10.3

 

 

 

2.HttpUtils工具

public class HttpUtils {
    private static Logger Log  = LoggerFactory.getLogger(HttpUtils.class);


    // 1.使用get方式发送报文
    public static String getData(String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        try{
            CloseableHttpResponse response = client.execute(get);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                Log.info("远程调用成功.line={}",response.getStatusLine());
                HttpEntity entity = response.getEntity();
                return EntityUtils.toString(entity,"UTF-8");
            }
            return  null;
        }catch (IOException e){
            Log.error("远程调用失败.e={}",e.getMessage());
        }
        return  null;
    }
    public static String post(String type,String url,String data){
        String result = "";
        switch (type){
            case "xml":
                result =  postData(url,data,ContentType.APPLICATION_XML.toString());
                break;
            case "json":
                result = postData(url,data,ContentType.APPLICATION_JSON.toString());
                break;
            default:
                break;
        }
        return  result;
    }


    // 使用POST方法发送XML或者json数据
    public static String postData(String url, String xmlData,String contentType){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-type",contentType);
        try{
            StringEntity entity = new StringEntity(xmlData);
            post.setEntity(entity);
            CloseableHttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                Log.info("远程调用成功.line={}",response.getStatusLine());
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity);
            }
        }catch (IOException e){
            Log.error("远程调用失败.e={}",e.getMessage());
        }
        return  null;
    }

    // 使用POST方法发送FORM表单数据
    public static String postForm(String url, Map map){
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-type",ContentType.APPLICATION_FORM_URLENCODED.toString());
        try{
            List list = new ArrayList<>();
            for(Map.Entry entry : map.entrySet()){
                list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
            }

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list);
            post.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse response = client.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode==200){
                Log.info("远程调用成功.line={}",response.getStatusLine());
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity);
            }
        }catch (IOException e){
            Log.error("远程调用失败.e={}",e.getMessage());
        }
        return  null;
    }





}

3.Controller 返回html或者js给前端

 

 

 

@Controller
public class HtmlController {
    private static final Logger LOGGER = LoggerFactory.getLogger(HtmlController.class);

    @RequestMapping("/clientToHtml")
    public void clientToHtml(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String body = HttpUtils.getData("http://www.baidu.com");//body为获取的html代码
        Document doc = Jsoup.parse(body);
        LOGGER.info("返回页面内容:",doc.outerHtml());
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(doc.outerHtml());
    }


    @RequestMapping("/clientToJs")
    public String clientToJs(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Map map = new HashMap<>();
        map.put("type","1");
        String body = HttpUtils.postForm("http://localhost:28082/demo/postJs",map);//body为获取的js代码
        LOGGER.info("返回页面内容:body={}",body);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(body);
        return "index";
    }

    @RequestMapping("/postJs")
    @ResponseBody
    public String postJs(String type){
        LOGGER.info("接收到请求.type=1",type);
        StringBuilder sb = new StringBuilder();
        sb.append("");
        return sb.toString();
    }

}

4. index页面




    
    Title


Hello

页面效果:

Controller返回html效果:

httpclient请求链接返回html或者javascript并返回给浏览器_第1张图片

Js返回效果

httpclient请求链接返回html或者javascript并返回给浏览器_第2张图片

 

 

 

 

 

 

 

 

你可能感兴趣的:(【Java】)