利用 Java 实现接口 POST 请求测试

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:02   4963   0

下面这个postDemo类是java的post请求去调用http://localhost:8080/callBack的接口

public class postDemo {

private static HttpClient httpClient = new DefaultHttpClient();
private static HttpPost httppost;
private static HttpResponse response;
private HttpEntity entity;
private String postResult = null;

public static void main(String[] args) {

String loginURL = "http://localhost:8080/callBack";
// 创建一个httppost请求
httppost = new HttpPost(loginURL);
JSONObject jsonParam = new JSONObject();
jsonParam.put("Origin_File", Origin_File);
jsonParam.put("Batch_Status",Batch_Status);
jsonParam.put("File_List",File_List);
try {

StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");// 解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httppost.setEntity(entity);
response = httpClient.execute(httppost);
String strResult = EntityUtils.toString(response.getEntity());
System.out.println("查看返回的结果:" + strResult);


} catch (Exception e) {
e.printStackTrace();
}

httppost.releaseConnection();

}

}

下面这个是被调用的接口

@RestController
public class PhoneStatusController {
private static final Logger logger = LoggerFactory.getLogger(PhoneStatusController.class);
@RequestMapping("/hello1")
public String test() {
return "hello,this is a springboot demo";
}

@RequestMapping(value = "/callBack", method = RequestMethod.POST)
@ResponseBody
public JSONObject dxCallback(
HttpServletRequest request, HttpServletResponse response) throws IOException {
String content = "";
try {
content = IOUtils.toString(request.getInputStream(), "UTF-8");
} catch (IOException e) {
logger.info("failure! Exception: {}", e);
}
logger.info("Notify content: {}", content);
JSONObject json = JSON.parseObject(content);
//{"desc":"正常","phone":"13790719324","reqId":"yMrBmOAvnV4j5gXz9PVYj5","status":"0000"}
String Origin_File = json.getString("Origin_File");
String Process_Status = json.getString("Batch_Status");

logger.info("Origin_File: {}, Process_Status: {}", Origin_File, Process_Status);

JSONObject reqData = new JSONObject();
reqData.put("Origin_File", Origin_File);
reqData.put("Process_Status", 1);

return reqData;
}
}

最后返回结果是{"Process_Status":1,"Origin_File":"WDBR_SpecialList_20190315.dat"}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP