JAVA发送包含XML字符串的Post请求

标签 java xml post xmlhttprequest http-post

问题描述

我正在尝试编写一个向服务器发送 POST 请求的代码。由于服务器还不存在,我无法测试这部分代码。对于该请求,我必须将 XML 作为字符串发送,如下所示:

String XMLSRequest = "<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><AuthenticationHeader><Username>Victor</Username><Password>Apoyan</Password></AuthenticationHeader></soapenv:Body></soapenv:Envelope>"

解决方案

String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = String.format("request=%s", XMLSRequest);

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

问题

这是将字符串(类似 XML 的字符串)作为 POST 请求发送到服务器的正确方法吗?

最佳答案

发布 SOAP request ,您可能希望将 xml 写入请求正文。您不想将其写为请求的参数。

String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection con = (HttpsURLConnection) obj.openConnection();

// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");

// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream(); //get output Stream from con
os.write( XMLSRequest.getBytes("utf-8") );
os.close();

关于JAVA发送包含XML字符串的Post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25104556/

相关文章:

java - java中FOR LOOP中局部变量的作用域

jquery - 通过 jQuery AJAX 传递 XML 的不同方式

javascript - 动态表到 JSON

php - Guzzle post 请求到自己的服务器导致 `404 Not Found`

php - 如何将 GET 和 POST 数据传递给 php 可执行文件?

java - 如何在 Web 应用程序(Spring/Vaadin)中为每个用户创建和维护一个 jdbc 连接?

java - 从 XML 读取信用卡号列表

java - Android Studio 的按钮和 Activity

c# - Visual Studio 工具箱代码片段

java - 解码时出现 JAXB 意外元素