【问题标题】:How to write a very basic POST client in Java如何用 Java 编写一个非常基本的 POST 客户端
【发布时间】:2015-12-03 12:07:25
【问题描述】:

我必须用 Java 编写最基本的 POST 客户端。 它将一些参数发送到证书服务器。 参数应该是 JSON 编码的

我有附加代码,如何使参数 JSON 编码?

   String url = "http://x.x.x.x/CertService/revoke.php";

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "serialnumber=C02G8416DRJM&authtoken=abc&caauthority=def&reason=ghi";

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

    int responseCode = con.getResponseCode();

【问题讨论】:

    标签: java json http post


    【解决方案1】:

    您可以将您的内容类型设置为 application/json 并发送 json 字符串吗?

    con.setRequestProperty("Content-Type", "application/json");
    

    【讨论】:

      【解决方案2】:

      您在示例中发布的文本看起来像是 application/x-www-form-urlencoded。要获取 application/json 编码,请将参数准备为映射,然后使用多个 JSON 编码库中的任何一个(例如,Jackson)将其转换为 JSON。

      Map<String,String> params = new HashMap<>();
      params.put("serialnumber", "C02G8416DRJM");
      params.put("authtoken", "abc");
      ...
      ObjectMapper mapper = new ObjectMapper();
      OutputStream os = con.getOutputStream();
      mapper.writeValue(os, params);
      os.flush();
      os.close();
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-13
        • 2020-04-03
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 2011-12-01
        • 1970-01-01
        相关资源
        最近更新 更多