如何使用Java中的post方法发送url编码的数据

时间:2018-07-19 11:49:33

标签: java post httpurlconnection

我正在尝试使用Java中的HttpURLConnection方法发送url编码的数据。客户端从Soap UI测试器共享了以下字符串作为示例请求:

http://www.clienturl.com/payment?username=bk&password=bk&customerid=100039085&amountcredit=100&operationdate=2018-07-17&event=9977773&reference=2323900&account=00000000&valuedate=2018-07-17&terminal=00010

我尝试了使用Java发送数据的所有组合。我收到的响应代码为200,但响应显示请求中缺少必需的参数。如果我的代码有任何错误,请在编写请求时提供帮助。

StringBuffer response = new StringBuffer();
    String EndPointURL = url;
    String requestXML = "username=bk&password=bk&customerid=78233209438&amountcredit=100&operationdate=2018-07-17&event=9977773&reference=13903232&account=000000&valuedate=2018-07-17&terminal=00010";
    String encodedData = URLEncoder.encode(requestXML, "UTF-8");
    System.out.println("Encoded data: " + encodedData);

    URL localURL = new URL(EndPointURL);
    HttpURLConnection con = (HttpURLConnection) localURL.openConnection();
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Accept-Charset", charset);
    con.setRequestProperty("Content-Length", Integer.toString(encodedData.length()));
    OutputStream os = con.getOutputStream();

1 个答案:

答案 0 :(得分:0)

如果您使用的是Okhttp3,请使用以下代码:


GRANT EXECUTE ON DBMS_CQ_NOTIFICATION TO user_name;
GRANT CHANGE NOTIFICATION TO user_name;

对于Unirest:

OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "string-that-you-need-to-pass-in-body");
Request request = new Request.Builder()
  .url("url-string")
  .post(body)
  .addHeader("content-type", "application/x-www-form-urlencoded")
  .build();

Response response = client.newCall(request).execute();