我正在尝试触发POST请求。我发送的数据是XML格式(我通过JAXB这样做),但我必须发送一个请求参数。我的问题是关于内容类型(我在代码中添加了一些注释)。我应该使用哪一个?
见下面我的代码:
private V callAndGetResponse(K request, Class<K> requestClassType, Class<V> responseClassType) throws Exception {
JAXBContext jaxbContext = JAXBContext.newInstance(requestClassType, responseClassType);
Marshaller marshaller = jaxbContext.createMarshaller();
// set properties on marshaller
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", String.format(XML_HEADER_FORMAT, dtd));
marshaller.marshal(request, System.out);
URL wsUrl = new URL(primaryEndpointUrl);
HttpURLConnection connection = openAndPrepareConnection(wsUrl);
tryToMarshallWsRequestToOutputStream(request, marshaller, connection);
printDebug(connection);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Object response = unmarshaller.unmarshal(connection.getInputStream());
// cleanup
connection.disconnect();
return responseClassType.cast(response);
}
private HttpURLConnection openAndPrepareConnection(URL wsUrl) throws IOException {
HttpURLConnection connection = (HttpURLConnection) wsUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept", "application/xml");
connection.setRequestProperty("Accept-Charset", charset);
// Both types ? Doesn't work
connection.setRequestProperty("Content-Type", "application/xml;application/x-www-form-urlencoded");
// Only app/xml ? it seems that query param is not added to request
connection.setRequestProperty("Content-Type", "application/xml");
// Only app/query param ? it seems that xml is not added to request
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
return connection;
}
private void tryToMarshallWsRequestToOutputStream(K request, Marshaller jaxbForRequestMarshaller,
HttpURLConnection connection) throws JAXBException, IOException {
OutputStream outputStream = null;
try {
outputStream = connection.getOutputStream();
jaxbForRequestMarshaller.marshal(request, outputStream);
addQueryParameters(outputStream);
}
finally {
tryToClose(outputStream);
}
}
private void addQueryParameters(OutputStream outputStream) throws IOException {
String value = "none";
String query = String.format("xmlmsg=%s", URLEncoder.encode(value, charset));
outputStream.write(query.getBytes(charset));
}
protected void tryToClose(OutputStream outputStream) throws IOException {
if (outputStream != null) {
outputStream.close();
}
}
非常感谢!
答案 0 :(得分:4)
好的,您正在处理两个不同的问题:
1)内容 - 身体的类型。在这种情况下,如果您的正文是XML正文,那么它应该是:
Content-Type: application/xml; charset="utf-8"
2)您的查询参数被剥离(或忽略)的事实。这是一个更复杂的问题。当表单通过HTTP Post提交时,它通常作为查询字符串参数发送,这看起来像可能发生的事情。你能得到一些关于发送内容的线索吗?可能您需要自己解析参数而不是尝试将它们解析为表单主体。
如果您需要发送两种不同类型的数据,您可以考虑发送类似多部分表单,或发送一种正文类型,以及添加额外数据作为标题。