繁体   English   中英

Java从Servlet调用带有POST中参数的第三方URL

[英]Java call thirdparty url with parameters in POST from a servlet

从我的Java Web应用程序中,我想调用第三方站点的URL。 第三方url需要一些只能通过post接受的输入参数。这些输入不是来自使用我网站的客户。 最后,第三方页面将显示在我网站的iframe中。 我可以使用一个jsp文件来做到这一点,该文件将隐藏这些输入,并按如下所示提交onload表单:

<body onload="document.form1.submit()">
    <%  
        response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
        response.setHeader("Pragma","no-cache"); //HTTP 1.0
        response.setDateHeader ("Expires", 0);
    %>  
<FORM METHOD="post" ACTION="<%= (String)request.getAttribute("thridpartyurl") %>" id=form1 name=form1>
<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="rightbox"> 
    <tr>
        <td>
        <input type="hidden" name="param1" value="<%= (String)request.getAttribute("param1") %>">
                <input type="hidden" name="param2" value="<%= (String)request.getAttribute("param2") %>">

        </td>
    </tr>
</table>    
</form>
</body>

但我想避免这种jsp提交。 我正在寻找一种无需JSP参与的方法。 有什么办法可以在Java中做到这一点。 通过我的小搜索,我理解为response.sendRedirect无法提交帖子。 并且dispatcher.forward(request, response)不能用于外部项目url。

请帮忙。

问候,

下面是调用任何http网址的Java代码。

    String url = "thirdparty site url";

    URL obj = new URL(url);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");


    String urlParameters = "param1=value1&param2=value2";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM