包含XML字符串的JAVA发送Post请求 问题描述

包含XML字符串的JAVA发送Post请求 问题描述,java,xml,post,xmlhttprequest,http-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/"><so

我正在尝试编写一个代码,向服务器发送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>"
问题: 这是将字符串(类似XML的字符串)作为POST请求发送到服务器的正确方法吗?

要发布,您需要将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();

首先,您需要序列化为JSON,然后通过HTTP发送。不确定为什么要在XML中附加“request=”,除此之外它看起来还可以。@RomanC您能举一些例子来回答如何通过HTTP连接以正确的方式发送XML字符串吗?@kharyam您的意思是
string urlParameters=XMLSRequest这样可以吗?您不应该使用http connection.urlConnection不工作我的jax rs web服务,该服务是lib为此工作添加的
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();