我需要从 Java 代码本身调用控制器。控制器如下,
@RequestMapping(value = "temp", method = RequestMethod.POST)
@ResponseBody
public String uploadDataFromExcel(@RequestBody Map<String, String> colMapObj, @ModelAttribute ReqParam reqParam) {
}
我正在尝试使用 http post 调用上述控制器,如下所示,
String url ="http://localhost:8081/LeadM" + "/temp/?searchData="+ reqParam.getSearchData()+" &exportDiscardRec=" + reqParam.isExportDiscardRec() + "&fileName=" + reqParam.getFileName() + "&sheetName=" + reqParam.getSheetName() + "&importDateFormat=" + reqParam.getImportDateFormat() + "&selectedAddressTypes="+ reqParam.getSelectedAddressTypes() + "&duplicatesHandleOn=" + reqParam.getDuplicatesHandleOn() + colMapObj;
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
InputStream rstream = entity.getContent();
jsonObject = new JSONObject(new JSONTokener(rstream));
其中 reqParam 是一个类对象是类对象, colMapObj 是我想传递给上述控制器的地图。但是,当执行 http post 时,它会在 url 中给出异常。如果有人知道正确的方法,请提出建议,谢谢。
URL 不适用于空格。从上面的代码中:“ &exportDiscardRec=" 为避免此类问题,请尽可能使用URIBuilder或类似的东西。
现在对于请求,您没有正确构建您的请求,例如您没有提供正文。检查以下示例:
Map<String, String> colMapObj = new HashMap<>();
colMapObj.put("testKey", "testdata");
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
JSONObject body = new JSONObject(colMapObj);
StringEntity entity = new StringEntity(body.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse response = client.execute(httpPost);
System.out.println(response.getEntity().toString());
client.close();
更多示例只是谷歌“apache http客户端发布示例”(例如http://www.baeldung.com/httpclient-post-http-request)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句