調用第三方接口,傳輸二字節流,每次批量傳輸都有一部分傳輸失敗,接口響應超時,返回400,不管修改超時時間多久都不成功
一.使用feign方式
接口調用使用feign包裝第三方接口
@FeignClient(name = "xxx-service", url = "${url}", configuration = { FeignClientConfig.class })
public interface ServiceFeign {
@RequestMapping(value = "${a.url}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public AResponse getA(ARequest request);
}
調用位置
public class TestA{ @Autoware private ServiceFeign serviceFeign; public xx methodA(xxx){ serviceFeign.getA(xxx); } }
開啟feign日志發現報400,第三方無響應返回
懷疑時feign的問題故換成http的:
/** * 以HTTP post方式訪問指定URL * @param url 訪問URL * @param jsonObject json對象 * @return 服務器響應內容 */ public static String jsonPost(String url, String jsonObject) { PostMethod method = new PostMethod(url); String body = null; if (StringUtils.isNotBlank(jsonObject)) { try { method.addRequestHeader("Content-type", "application/json; charset=utf-8"); method.addRequestHeader("Accept", "text/xml,text/javascript,text/html,application/json"); RequestEntity requestEntity = new StringRequestEntity(jsonObject, "application/json", "utf-8"); method.setRequestEntity(requestEntity); httpClient.executeMethod(method); InputStream inputStream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = br.readLine()) != null) { stringBuffer.append(str); } body = stringBuffer.toString(); log.info("http返回結果{}",body); } catch (Exception e) { log.error("連接異常:"+e.getMessage(),e); } finally { method.releaseConnection(); } } return body; }
發現還是一樣的問題(fegin底層可能也是這種方式實現的),
最后解決方法:使用map方式成功了
/** * 以HTTP post方式訪問指定URL * @param url 訪問URL * @param paramData map對象 * @return 服務器響應內容 */ @SuppressWarnings("deprecation") public static String jsonPost(String url, Map<String, Object> paramData) { PostMethod method = new PostMethod(url); String body = null; if (method != null && paramData != null) { try { method.addRequestHeader("Content-type", "application/json; charset=utf-8"); method.addRequestHeader("Accept", "application/json"); String jsonObject = JSONObject.toJSONString(paramData); method.setRequestBody(jsonObject); httpClient.executeMethod(method); log.info("http-jsonPost-jsonObject:" + method.getResponseBodyAsString()); InputStream inputStream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); StringBuffer stringBuffer = new StringBuffer(); String str = ""; while ((str = br.readLine()) != null) { stringBuffer.append(str); } body = stringBuffer.toString(); }catch(SocketTimeoutException te){ log.error("連接超時:"+te.getMessage()); }catch (Exception e) { log.error("連接異常:"+e.getMessage(),e); } finally { method.releaseConnection(); } } return body; }
記錄一下,具體原因不是很明白!!!
