我已經編寫了一個Web服務,現在正在編寫一個測試程序以從外部執行集成測試。我正在使用apache httpclient 4.3寫我的測試人員。根據這裏的代碼:http://hc.apache.org/httpcomponents-client-4.3.x/quickstart.html和這裏:http://hc.apache.org/httpcomponents-client-4.3.x/tutorial/html/fundamentals.html#d5e186我寫了下面的代碼。HttpPost請求不成功
Map<String, String> parms = new HashMap<>();
parms.put(AirController.KEY_VALUE, json);
postUrl(SERVLET, parms);
...
protected String postUrl(String servletName, Map<String, String> parms)
throws AirException{
String url = rootUrl + servletName;
HttpPost post = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for(Map.Entry<String, String> entry:parms.entrySet()){
BasicNameValuePair parm = new BasicNameValuePair(entry.getKey(), entry.getValue());
nvps.add(parm);
}
try {
post.setEntity(new UrlEncodedFormEntity(nvps));
} catch (UnsupportedEncodingException use) {
String msg = "Invalid parameters:" + parms;
throw new AirException(msg, use);
}
CloseableHttpResponse response;
try {
response = httpclient.execute(post);
} catch (IOException ioe) {
throw new AirException(ioe);
}
String result;
if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
result = processResponse(response);
}
else{
String msg = MessageFormat.format("Invalid status code {0} received from query {1}.",
new Object[]{response.getStatusLine().getStatusCode(), url});
throw new AirException(msg);
}
return result;
}
此代碼成功到達我的servlet。在我的servlet,我有(使用Spring的一個AbstractController):
protected ModelAndView post(HttpServletRequest request, HttpServletResponse response) {
String json = String.valueOf(request.getParameter(KEY_VALUE));
if(json.equals("null")){
log.info("Received null value.");
response.setStatus(406);
return null;
}
而這個代碼總是落入空參數代碼,並返回406
我敢肯定,我失去了一些東西簡單,但看不到它是什麼。
'parms'包含什麼? –
@SotiriosDelimanolis看看前面幾行代碼。 – Thom
是的,但'json'有什麼價值?在控制器中'AirController.KEY_VALUE'與'KEY_VALUE'具有相同的值嗎? –