我正在搜索spring boot的工作代码示例/片段,以将json内容发布到HTTPS静态Web服务(在python中开发)。下面是执行相同操作的独立程序的示例代码,但是我想在Spring Boot Restful应用中进行操作。我在Google中发现了许多示例,并且堆栈溢出example example都是为了获取请求,而不是我要查找的内容。有人请分享“ 使用Spring Boot服务的https发布请求” 的完整工作示例。 提前致谢。
import java.io.PrintStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HttpsURLConnection;
public class App{
public static void main(String []args) throws NoSuchAlgorithmException, KeyManagementException{
String https_url = "https://192.168.4.5:55543/books";
String content = "{\"data\":{\"a\"}}";
System.setProperty("javax.net.useSystemProxies", "true");
System.setProperty("javax.net.ssl.keyStore", "C:/cert/client.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "testdev");
System.setProperty("javax.net.ssl.trustStore", "C:/cert/server.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "testdev");
System.setProperty("jdk.tls.client.protocals", "TLSv1.2");
System.setProperty("https.protocals", "TLSv1.2");
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> { return true;});
URL url = new URL(https_url);
HttpsURLConnection https_con = (HttpsURLConnection) url.openConnection();
https_con.setRequestProperty("Content-Type", "application/json");
https_con.setRequestMethod("POST");
https_con.setDoOutput(true);
PrintStream ps = new PrintStream(https_con.getOutputStream());
ps.println(content);
ps.close();
https_con.connect();
https_con.getResponseCode();
https_con.disconnect();
}
}
答案 0 :(得分:0)
好吧,这里是forked Github repo。
以下是我所做的更改:
secure-server
->添加了具有简单字符串有效负载的发布端点:
@RestController
public class HomeRestController {
//...
@PostMapping(value = "/", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String consumeData(@RequestBody String data, Principal principal){
return String.format("Hello %s! You sent: %s", principal.getName(), data);
}
}
secure-client
->将调用添加到该post方法:
@RestController
public class HomeRestController {
// . . .
@GetMapping("/post")
public String post() throws RestClientException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String data = "Test payload";
HttpEntity<String> request = new HttpEntity<>(data, headers);
return restTemplate.postForEntity("https://localhost:8443", request , String.class ).getBody();
}
}
因此,当您以以下方式呼叫客户端端点时:
http://localhost:8086/post
您将得到答复:
Hello codependent-client! You sent: Test payload