在Java中通过post方法发送表单

时间:2015-05-22 12:13:41

标签: grails paypal

我需要从Java或Groovy代码发送此表单:

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
    <input type="hidden" name="business" value="xxx@xxx.com">
    <input type="hidden" name="currency_code" value="EUR">
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="upload" value="1">
    <input type="hidden" name="item_name_1" value="zzzzz zzzz zzz">
    <input type="hidden" name="item_number_1" value="11111111">
    <input type="hidden" name="item_quantity_1" value="2">
    <input type="hidden" name="amount_1" value="11.11">

    <input type="image" src="xxxxxxx" border="0" name="submit">
    <img border="0" src="xxxxxxxxxxxxx" width="1" height="1">
</form>

我需要代码发送发送此表单的相同请求。

这不是正常的帖子请求。提交此HTML时,您将重定向到PayPal。我需要从Java重定向到PayPal,但是通过post方法发送数据。

1 个答案:

答案 0 :(得分:0)

试试这段代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;  
import java.net.MalformedURLException;
import java.net.URL;


public class Sender {

public static void main(String[] args) {


    sendPost("xxx@xxx.com", "EUR", "_cart", "1", "zzzzz zzzz zzz", "11111111", "2", "11.11");
}

public static String sendPost(String business,String currency_code,String cmd,String upload,String item_name_1,String item_number_1,
        String item_quantity_1,String amount_1
        )
{
    try {
        URL url = new URL("https://www.sandbox.paypal.com/cgi-bin/webscr");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setRequestProperty("Content-Type", "text/html");
        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
        String request="business="+business+"&currency_code="+currency_code+
                "&cmd="+cmd+"&upload="+upload+"&item_name_1="+item_name_1+"&item_number_1="+item_number_1+
                "&item_quantity_1="+item_quantity_1+"&amount_1="+amount_1;
        writer.write(request);
        writer.flush();
        System.out.println("Code:"+conn.getResponseCode());
        System.out.println("mess:"+conn.getResponseMessage());


        String response="";
        BufferedReader reader = new BufferedReader(new  InputStreamReader(conn.getInputStream(),"UTF-8"));
        String line;
        while ((line = reader.readLine()) != null) {
            response+=line;
        }

        System.out.println(new String(response.getBytes(),"UTF8"));
        writer.close();
        reader.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}

}