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

时间:2017-10-20 03:06:01

标签: java curl tracing

我有一个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请求,它将执行相同的操作。我对此没有任何想法。提前感谢那些需要时间回应的人。

1 个答案:

答案 0 :(得分:0)

有多种方法可以做到这一点。首先,由于您要发送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 
}