java - 将一个 API 的 requestbody 发送到另一个 API
问题描述
这是我的代码
private static final String MEDIA_TYPE = "application/json";
private static final String FORMAT = "UTF-8";
private static String baseServiceUrl;
private static String apiServiceUrl;
@RequestMapping("/")
public ResponseEntity<?> getMessage() throws Exception {
logger.info("Started");
try {
messageProcessor.getMessage("test service");
// Read from request
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String data = buffer.toString();
StringRequestEntity requestEntity = null;
HttpClient httpclient = new HttpClient();
int statusCode;
logger.info("RequestBody"+data);
baseServiceUrl="http://localhost:8080/services";
apiServiceUrl="/services/rest/json";
StringBuffer eventResponse = new StringBuffer();
requestEntity = new StringRequestEntity(data, MEDIA_TYPE, FORMAT);
PostMethod postMethod = new PostMethod(baseServiceUrl+apiServiceUrl);
postMethod.setRequestEntity(requestEntity);
statusCode = httpclient.executeMethod(postMethod);
logger.info("Status code"+statusCode);
}
catch (Exception ex) {
logger.error("Exception occurs ", ex);
return new ResponseEntity("Internal server error !!", HttpStatus.INTERNAL_SERVER_ERROR);
}
return new ResponseEntity("Successfully called the service!!", HttpStatus.OK);
}
我想获取一个 API 的请求体并发送到另一个 API。json 是我的请求体。但在这段代码中,我得到的状态码为 400。谁能帮我解决这个问题
解决方案
在您的代码中,您将请求正文作为字符串读取,您能否共享记录的请求正文。HTTP 响应代码 400 对应于 BAD 请求。因此,您尝试访问的端点可能不同,或者请求正文有问题。尝试/services
从您的中删除apiServiceUrl
以更正 url 路径。此外,由于您很可能将 json 作为请求正文,请尝试以下方法:
String json = "{"id":1,"name":"xxxx"}";
StringEntity entity = new StringEntity(json);
postMethod.setEntity(entity);
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
确保您使用 BufferedReader 从请求中读取的字符串采用reader = request.getReader();
适当的 json 格式。
推荐阅读
- elasticsearch - 你能说出使用 Kibana 存储多长时间的日志吗?
- python - pygame多键射击冷却
- android - 如何使用 GPUImage
- python - 如何在 Python 中覆盖定时器
- java - 通过 Google 和 Yandex 进行 OAuth 身份验证
- admob - 此中介组仍在投放广告,但存在一个或多个影响其效果的问题。展开此中介组了解更多详情
- r - 将 gsub 与数据帧一起使用会得到奇怪的结果,如何将 gsub 与数据帧一起使用
- azure - 如何连接到安装在 Azure 上的多个节点的 elasticsearch 集群?如何获得弹性搜索端点?
- apache-spark - 如何提高 groupby 聚合的执行时间以计算 spark 中的百分位数?
- azure-logic-apps - 如何在 Azure 逻辑应用程序中实现顺序护航