如何卷曲调用转换为Java URLConnection的通话
问题描述:
我有卷曲的命令:如何卷曲调用转换为Java URLConnection的通话
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发送到您的网址的示例代码。
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
}
感谢您的回复。我会试试这个。 – Will
你试过这个吗? –
是的,它的工作。非常感谢。 – Will