要在 java 裡接收 post 收到的 json,範例如下:
Read the Response From Input Stream
Get the input stream to read the response content. Remember to use try-with-resources to close the response stream automatically.
Read through the whole response content, and print the final response string:
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
如果是要透過 java 送出,範例如下:
Here is what you need to do:
- Get the Apache
HttpClient
, this would enable you to make the required request - Create an
HttpPost
request with it and add the headerapplication/x-www-form-urlencoded
- Create a
StringEntity
that you will pass JSON to it - Execute the call
The code roughly looks like (you will still need to debug it and make it work):
// @Deprecated HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity("details={\"name\":\"xyz\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
} finally {
// @Deprecated httpClient.getConnectionManager().shutdown();
}