在Java上发出发布请求

时间:2018-08-08 13:20:04

标签: java xml curl post

你好,我在Java领域有点新手,我需要帮助。

有人可以向我解释如何发出这样的请求:

curl --data @FILE.xml -H 'content-type: application/xml' 'Host: URL' --cert ./FILE.crt:FILEPASS --key ./FILE.pem URL-REQUEST

(这已经在linux终端上工作了)使用Java代码。这句话发送一个XML文件。

谢谢您,祝您愉快。

1 个答案:

答案 0 :(得分:0)

您可以使用Apache HttpClient之类的库:

String url = "https://foourl.com"; 

TrustStrategy acceptingTrustStrategy = (cert, authType) -> true;
SSLSocketFactory sf = new SSLSocketFactory(
  acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", 8443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

HttpClient client = new DefaultHttpClient(ccm);
HttpPost post = new HttpPost(url);

// set header
post.setHeader("User-Agent", "my-user-agent");
post.setHeader("Content-Type", "application/xml");

String xmlString = getXmlAsString();

List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("xml", xmlString));

post.setEntity(new UrlEncodedFormEntity(urlParameters));

HttpResponse response = client.execute(post);
System.out.println("Response Code : " + 
                            response.getStatusLine().getStatusCode());

BufferedReader rd = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));

StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
    result.append(line);
}

System.out.println(result.toString());

检查以下链接:https://www.baeldung.com/httpclient-post-http-request https://www.baeldung.com/httpclient-ssl

请记住,您需要将xml文件解析为字符串。检查此链接:https://www.journaldev.com/1237/java-convert-string-to-xml-document-and-xml-document-to-string