[英]How to convert a cURL call into a Java URLConnection call
I have a cURL command:我有一个 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
I need to create an HTTP Request in Java API which will do the same thing.我需要在 Java API 中创建一个 HTTP 请求,它会做同样的事情。 I don't have any idea regarding this.
我对此没有任何想法。 Thank you in advance for those who will take time to respond.
预先感谢那些愿意花时间回复的人。
There are multiple ways to do it.有多种方法可以做到。 Firstly, since you want to send a JSON object, you might want to use a JSON library, for example, Google's gson.
首先,由于您要发送 JSON 对象,因此您可能需要使用 JSON 库,例如 Google 的 gson。 But to make it easy you can just send the request as a
String
.但为了方便起见,您可以将请求作为
String
发送。 Here is a sample code that sends your JSON to your URL.这是将您的 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.