繁体   English   中英

如何将 cURL 调用转换为 Java URLConnection 调用

[英]How to convert a cURL call into a Java URLConnection call

我有一个 cURL 命令:

curl -d '{"mobile_number":"09178005343", "pin":"1111"}' -H "Content:Type: application/json" -H "X-Gateway-Auth:authentication" -X POST https://localhost:9999/api/traces/%2f/login

我需要在 Java API 中创建一个 HTTP 请求,它会做同样的事情。 我对此没有任何想法。 预先感谢那些愿意花时间回复的人。

有多种方法可以做到。 首先,由于您要发送 JSON 对象,因此您可能需要使用 JSON 库,例如 Google 的 gson。 但为了方便起见,您可以将请求作为String发送。 这是将您的 JSON 发送到您的 URL 的示例代码。

HttpClient httpClient = HttpClientBuilder.create().build(); 

try {

    HttpPost request = new HttpPost("https://localhost:9999/api/traces/%2f/login");
    StringEntity params =new StringEntity("{\"mobile_number\":\"09178005343\", \"pin\":\"1111\"");
    request.addHeader("content-type", "application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);

    //Do what you want with the response

}catch (Exception ex) {

    //If exception occurs handle it

} finally {
     //Close the connection 
}

暂无
暂无

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

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