【发布时间】:2014-07-07 15:45:23
【问题描述】:
以下代码是 servlet 的一部分,它获取 cookie 值并将请求发送到具有相同 cookie 值和附加标头的另一个服务。
我在 responseCode = serviceUrlConnection.getResponseCode(); 和 is = serviceUrlConnection.getInputStream(); 上收到 HTTP 400 响应。
使用相同的输入值(cookie 和附加标头),我能够使用 SOAP UI 从服务中获得正确的输出。谁能指出错误。
URL serviceURL = new URL(serviceUrlInput);
logger.info(" Validate Test token service Url" + serviceUrlInput);
URLConnection serviceConnection = serviceURL.openConnection();
HttpURLConnection serviceUrlConnection = (HttpURLConnection)serviceConnection;
serviceUrlConnection.setRequestProperty("Content-Type", "application/json");
serviceUrlConnection.setRequestProperty("charset", "UTF-8");
String TestCookieValue = null;
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("Test")) {
//TestToken = cookies[i].getValue();
TestCookieValue = cookies[i].getValue();
logger.info("Test cookie : " + "Test=" +TestCookieValue);
//serviceUrlConnection.setRequestProperty("Cookie", TestCookie.substring(0, TestCookie.indexOf(';')));
serviceUrlConnection.setRequestProperty("Cookie", "Test=" +TestCookieValue);
break;
}
}
}
//Set the timestamp in the header
Date javaUtilDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String formattedDateTime = formatter.format(javaUtilDate);
serviceUrlConnection.setRequestProperty("timestamp", formattedDateTime);
logger.info(adapterDescription + " :: timestamp added with value :: " + formattedDateTime);
//Set the transactionId header
UUID uuid = java.util.UUID.randomUUID();
serviceUrlConnection.setRequestProperty("transactionId", uuid.toString());
logger.info(adapterDescription + " :: transactionID added with value :: " + uuid.toString());
//Set the sourceSystem header
String sourceSystem = + InetAddress.getLocalHost().getHostName();
serviceUrlConnection.setRequestProperty("sourceSystem", sourceSystem);
logger.info(adapterDescription + " :: sourceSystem added with value :: " + sourceSystem);
int responseCode;
serviceUrlConnection.setDoOutput(true);
wr = new DataOutputStream(serviceUrlConnection.getOutputStream());
wr.writeBytes("");
logger.info(adapterDescription +" :: " + wr);
responseCode = serviceUrlConnection.getResponseCode();
logger.info(adapterDescription +":: responseCode :: " + responseCode);
is = serviceUrlConnection.getInputStream();
【问题讨论】:
-
HTTP 400 是“错误请求”,因此很明显,您的代码没有执行您正在调用的任何服务 URL 想要的操作。在此基础上,我不同意您的说法,即您的代码和 SoapUI 正在生成完全相同的请求。您是否尝试过使用 HTTP 嗅探器工具/浏览器插件来记录这两个请求并检查差异?