【发布时间】:2018-01-24 20:44:17
【问题描述】:
我有一个 springboot 项目,它只需要使用 gson 将其转换为 HashMap 的 POST JSON 字符串。我使用 Postman 作为 POST 进行了测试,并将正文添加为 props,并使用像 {'fistname': 'John', 'lastname' : 'Doe'} 这样的 json 字符串,转换为 props = {'fistname': 'John', 'lastname' : 'Doe'}。它按预期工作
@RequestMapping(value = "/rest", method = RequestMethod.POST)
protected String parse(@RequestParam("props") String props) {
Gson gson = new Gson();
Map<String, String> params = new HashMap<String, String>();
params = gson.fromJson(props, Map.class);
// Rest of the process
}
另一方面,我有一个JavaEE项目,需要调用这个API
protected void callREST() {
try {
String json = someClass.getDate() //retrieved from database which is stored as json structure
Map<String, String> props = gson.fromJson(json, Map.class);
URL url = new URL("http://localhost:9090/myApp/rest");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
System.out.println(props.toString());
wr.writeBytes(json.toString());
wr.flush();
wr.close();
if(conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed :: HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
System.out.println("Output from Server ... \n");
while((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch(Exception e) {
//print stack trace
}
}
我收到Failed :: HTTP error code : 400。我怀疑 spring boot 没有收到 props 变量中的数据,因为它是一个 POST 请求。
我应该在客户端代码中添加什么来传递道具和数据以使调用成功?
注意:JavaEE 运行在 tomcat :8080 上,Springboot 运行在 不同的tomcat:9090
【问题讨论】:
-
看看 Spring 的
RestTemplate类,它对此非常有用。
标签: java spring-boot