获取远程html插入到本地的网页里面(java+react实现)

in jsjava with 0 comment views: 324 times

需求: 通过编辑器生成的html被上传到阿里云的服务器,但是这个html 需要嵌入到另外的一个网页里面。

环境

Java代码

@RequestMapping(value = "/getHtml", method = RequestMethod.POST)
@UnNeedAdminId
@Unauthorize
public Object getHtml(@RequestBody Map<String, String> uri) throws Exception {
    URL url = new URL(uri.get("url"));
    URLConnection URLconnection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
    int responseCode = httpConnection.getResponseCode();
    String str = "";
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStream in = httpConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(in);
        BufferedReader bufr = new BufferedReader(isr);
        String lStr;
        while ((lStr = bufr.readLine()) != null) {
            str = str + lStr;
        }
        bufr.close();
    } else {
        str = "没有内容";
    }
    return str;
}

react 代码

export default class PHomeLog extends React.Component {
  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {
      siteContent: ""
    }
  }

  componentWillMount() {
    let id = this.props.id;
    let url = `http://XXXXXXX/${id}/XXX.html`;
    Fetch({
      host: "XXX",
      url: 'api/getHtml',
      body: {url},
      method: "POST",
    }).then((res)=>{
      this.setState({
        siteContent: res.data
      })
    })
  }
  createMarkup = (html) => {
    return {__html: html};
  };
    // 替换返回的html中被转义的字符
  escapeChars=(str)=> {
    str = str.replace(/&amp;/g, '&');
    str = str.replace(/&lt;/g, '<');
    str = str.replace(/&gt;/g, '>');
    str = str.replace(/&acute;/g, '\'');
    str = str.replace(/&quot;/g, '"');
    str = str.replace(/&brvbar;/g, '\\|');
    str = str.replace(/&#x27;/g, '\'');
    return str;
  }

  render() {
    let {siteContent} = this.state;
    siteContent = this.escapeChars(siteContent)
    return (
      <div>
        {
          siteContent?
            <div dangerouslySetInnerHTML={this.createMarkup(siteContent)}></div>:
            <div className="pusht">暂无日志……</div>
        }
      </div>
    );
  }
}
Responses