首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中检测HTTP中断

在Java中检测HTTP中断
EN

Stack Overflow用户
提问于 2017-04-04 19:31:16
回答 2查看 383关注 0票数 10

我正在从Java向外部系统发出REST调用。如果有任何连接中断,比如外部系统脱机,我需要一个侦听器来检测并执行相应的操作。如果我可以用Java实现这一点,请让我知道。最好是在Java 8中。

目前,如果我遇到这样的情况,我不会得到任何异常。我现在有以下代码

代码语言:javascript
复制
    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;
        }
    }
EN

回答 2

Stack Overflow用户

发布于 2017-06-18 04:45:15

如果使用Spring Boot,可以尝试名为Feign的声明式REST客户端

代码语言:javascript
复制
@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方法。这将使用从SomeRequestDTO获取的JSON body调用POST example.com/example/path/to/resource/34。如果请求失败,将调用YourTestFeignClientFallback内部的回退方法,然后返回一些默认数据。

票数 1
EN

Stack Overflow用户

发布于 2017-04-07 04:55:09

一旦Http响应/错误准备就绪,您就可以创建自己的侦听器,并使用传递回调用类的结果进行异步的HTTP调用。例如(有拼写错误):

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

代码语言:javascript
复制
public interface MyHttpListener {
  public httpComplete(MyHttpResults results);
}

在你的主类中实现。

代码语言:javascript
复制
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以接受侦听器

代码语言:javascript
复制
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);
      }
  }


 }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43206012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档