Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将cURL调用转换为javaurlconnection调用_Java_Curl_Trace - Fatal编程技术网

如何将cURL调用转换为javaurlconnection调用

如何将cURL调用转换为javaurlconnection调用,java,curl,trace,Java,Curl,Trace,我有一个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 我需要在JavaAPI中创建一个HTTP请求,它也会做同样的事情。我对此一无所知。提前感谢那些愿意花时间回复的人。有

我有一个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

我需要在JavaAPI中创建一个HTTP请求,它也会做同样的事情。我对此一无所知。提前感谢那些愿意花时间回复的人。

有多种方法。首先,因为您想要发送一个JSON对象,所以可能需要使用JSON库,例如Google的gson。但为了方便起见,您只需将请求作为
字符串发送即可。下面是将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 
}