检测Java中的HTTP中断

时间:2017-04-04 11:31:16

标签: java rest http java-8 http-post

我正在通过Java对外部系统进行REST调用。如果有任何连接中断,如外部系统脱机,我需要一个侦听器来检测并执行相应的操作。如果我能用Java实现这一点,请告诉我。最好是在Java 8中。

如果我遇到任何这种情况,目前我没有任何例外。我目前有以下代码

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(HOSTNAME);
    Invocation.Builder requestBuilder;

    requestBuilder = target.path(URL).request(MediaType.APPLICATION_JSON)
                                                .header(HEADER_AUTHORIZATION, AUTH_TOKEN);      
    Response response = null;
    if (HTTP_POST.equalsIgnoreCase(method)) {
        try{
        response = requestBuilder.post(Entity.entity(message, MediaType.APPLICATION_JSON_TYPE));
        }catch(Exception ex ){
            ex.printStackTrace();
        }
    } else if (HTTP_GET.equalsIgnoreCase(method)) {
        response = requestBuilder.get();
    } 

    String executeMessage = null;
    if(response != null){
        if (response.getStatus() == 200) {
            executeMessage = response.readEntity(String.class);         
            return new JSONObject(executeMessage);
        } else {
            executeMessage = response.readEntity(String.class);
            final JSONObject status = new JSONObject();
            status.put(STATUS_CODE, response.getStatus());
            status.put(STATUS_INFO, response.getStatusInfo());
            status.put("response", executeMessage);
            final JSONObject error = new JSONObject();
            error.put(ERROR, status);
            return error;
        }
    }

3 个答案:

答案 0 :(得分:1)

如果您使用Spring Boot,您可以尝试一个名为Feign的声明性REST客户端:

@FeignClient(url = "example.com", fallback = YourTestFeignClient.YourTestFeignClientFallback.class)
public interface YourTestFeignClient {

    @RequestMapping(method = RequestMethod.POST, value = "/example/path/to/resource/{id}")
    YourTestResponse requestExternalResource(@RequestParam("id") Long id, SomeRequestDTO requestDTO);

    @Component
    public static class YourTestFeignClientFallback implements YourTestFeignClient {

        @Override
        public YourTestResponse requestExternalResource(Long id, SomeRequestDTO requestDTO) {
            YourTestResponse testResponse = new YourTestResponse();
            testResponse.setMessage("Service unavailable");
            return testResponse;
        }

    }
}

您需要在此处执行的操作是在代码中注入YourTestFeignClient并在其上调用方法requestExternalResource。这将调用来自POST example.com/example/path/to/resource/34的JSON正文SomeRequestDTO。如果请求失败,将调用YourTestFeignClientFallback内的回退方法,然后返回一些默认数据。

答案 1 :(得分:0)

您可以创建自己的侦听器并使您的Http调用异步,并在HTTP响应/错误准备好后将结果传递回调用类。例如(使用拼写错误):

创建一个主类将实现的接口,您的Http客户端将使用...

public interface MyHttpListener {
  public httpComplete(MyHttpResults results);
}

在您的主要课程中实施。

public MyClass implements MyHttpListener {

  public void processHttpRequests(){
      for(int i=0; i<10; i++){
        // instantiate your Http Client class 
        HttpClient client = new HttpClient();

        // register the listener
        client.addHttpListener(this);

        // execute whatever URL you want and you are notified later when complete
        client.executeRequest("http://whatever");
     }
  }

  public httpRequestComplete(MyHttpResults results) {
    // do something with the results   
    results.getResponseCode();
    results.getRawResponse();
    results.whatever();
  }  

}

向HttpClient添加方法以接受侦听器

public class MyHttpClient {
    List<MyHttpListener> httpListenerList = new ArrayList();   

   // register listeners
   public void addHttpListener(MyHttpListener listener){
     httpListenerList.add(listener);
   }   

   // this is the method that processes the request
   public void executeRequest(String url) {

     // do whatever you were doing previously here   

     // optional POJO to wrap the results and/or exceptions
     MyHttpResults results = new MyHttpResults();
     results.withResponseCode(response.getResponseCode());
     results.withResponse(responseAsString);
     results.withException(ex);
     results.withWhatever(whatever);

     // notify listeners
     notify(results);

   }

  public void notify(MyHttpResults results){
      // notify listeners
      for(MyHttpListener listener : httpListenerList){
         listener.httpComplete(results);
      }
  }


 }

答案 2 :(得分:0)

如果要持续检查外部REST服务是否处于脱机状态,则必须设置某种定期ping请求。任何回复都意味着服务在线。在一段时间内没有回应意味着出现了问题。

你面临的问题来自java TCP Socket connect方法阻塞而且 java socket默认连接超时为0,实际上是无穷大,因为它在{{3 }}。

这意味着如果服务处于脱机状态,默认情况下您根本不会得到任何响应。

此处唯一正确且简单的选项是设置超时。在您的情况下,最简单的方法是使用Jersey Client属性设置,如下所示:

Client client = ClientBuilder.newClient();
// One second timeout may not be a really good choice unless your network is really fast
client.property(ClientProperties.CONNECT_TIMEOUT, 1000); 

只有在这种情况下,您才会收到异常,这表明您尝试ping的REST服务不接受连接。

根据实际网络功能谨慎设置超时,在某些情况下应超过5秒甚至15秒(例如WiFi和GPRS连接)。