使用RxJava和RxApacheHTTP的示例请求JSON不起作用

时间:2016-03-06 15:51:20

标签: java json rx-java reactive-programming

我试图使用RxJava检索请求的JSON对象!

在我的示例中,我有一个在浏览器中完美运行的宁静服务Java。

        //Object Data
   @XmlRootElement        
   public class Person {
        private String firstName;
        private String lastName;
        //getters and setters
    }

Restful Java

@Path("/persons")
public class PersonResource {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getBandas() {
        Person paulo = new Person();
        paulo.setFirstName("Paulo Henrique");
        paulo.setLastName("Pereira Santana");
//      
        List<Person> persons = new ArrayList<>();
        persons.add(paulo);


        return persons;
    }
}

结果(在浏览器中:http://localhost:8080/learn-java-rs/persons)有一个JSON对象:

{"Person": { 
             "firstName": "Paulo Henrique",
             "lastName": "Pereira Santana"
           }
}

我试图使用RxJava做同样的请求没有工作(或者不理解实现)。遵循:

public class Example {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try(CloseableHttpAsyncClient client = HttpAsyncClients.createDefault()) {

        client.start();

        Observable<Map> requestJson = requestJson(client, "http://localhost:8080/learn-java-rs/persons");
            Helpers.subscribePrint(requestJson.map(json -> json.get("firstName") + " " + json.get("lastName")), "person");      

    } catch (IOException e1) {
        e1.printStackTrace();
    }
}
private static Map<String, Set<Map<String, Object>>> cache = new ConcurrentHashMap<>();
@SuppressWarnings({"rawtypes","unchecked"}) 
private static Observable<Map> requestJson(HttpAsyncClient client,String url){
      Observable<String> rawResponse=ObservableHttp.createGet(url,client).toObservable().flatMap(resp -> resp.getContent().map(bytes -> new String(bytes,java.nio.charset.StandardCharsets.UTF_8))).retry(5).cast(String.class).map(String::trim).doOnNext(resp -> getCache(url).clear());
      Observable<String> objects=rawResponse.filter(data -> data.startsWith("{")).map(data -> "[" + data + "]");
      Observable<String> arrays=rawResponse.filter(data -> data.startsWith("["));

      Observable<Map> response=arrays.ambWith(objects).map(data -> {
        return new Gson().fromJson(data,List.class);
      }
    ).flatMapIterable(list -> list).cast(Map.class).doOnNext(json -> getCache(url).add((Map<String,Object>)json));
      return Observable.amb(fromCache(url),response);
    }
private static Observable<Map<String, Object>> fromCache(String url) {
    return Observable.from(getCache(url)).defaultIfEmpty(null)
            .flatMap(json -> (json == null) ? Observable.never() : Observable.just(json))
            .doOnNext(json -> json.put("person", true));
}

private static Set<Map<String, Object>> getCache(String url) {
    if (!cache.containsKey(url)) {
        cache.put(url, new HashSet<Map<String,Object>>());
    }
    return cache.get(url);
}

修改

public static <T> Subscription subscribePrint(Observable<T> observable,
        String name) {
    return observable.subscribe(
            (v) -> System.out.println(Thread.currentThread().getName()
                    + "|" + name + " : " + v), (e) -> {
                System.err.println("Error from " + name + ":");
                System.err.println(e);
                System.err.println(Arrays
                        .stream(e.getStackTrace())
                        .limit(5L)
                        .map(stackEl -> "  " + stackEl)
                        .collect(Collectors.joining("\n"))
                        );
            }, () -> System.out.println(name + " ended!"));
}

什么也没发生。

有人可以告诉我我错过了什么吗?

注意:我使用的是Rxjava api 1.1.0和rxapache-http-0.21.0

0 个答案:

没有答案