有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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) 个答案

  1. # 1 楼答案

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

    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();
    

    对于Unirest:

    HttpResponse<String> response = Unirest.post("url-string")
      .header("content-type", "application/x-www-form-urlencoded")
      .body("string-that-you-need-to-pass-in-body")
      .asString();