java 带有 asynchttpclient 的 JSON 帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16250053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 22:23:44  来源:igfitidea点击:

JSON post with asynchttpclient

javajerseyatmosphereasynchttpclient

提问by

I'm trying to do a POST request on a REST service with async support (provided by atmosphere). Here's what my service looks like:

我正在尝试对具有异步支持(由大气提供)的 REST 服务执行 POST 请求。这是我的服务的样子:

package co.damt.services;


import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;

import org.atmosphere.annotation.Broadcast;
import org.atmosphere.annotation.Suspend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * REST Web Service
 *
 * @author damt
 */
@Path("/")
public class GenericResource {

    private final Logger logger = LoggerFactory.getLogger(GenericResource.class);

    @Suspend(contentType = "application/json")
    @GET
    public String suspend() 
    {
        return "";
    }

    @Broadcast(writeEntity = false)
    @POST
    @Produces("application/json")
    public Message broadcast(Message message) 
    {
        logger.info(message.getAuthor()+"@"+message.getTime()+": "+message.getMessage());
        return message;
    }

}

I'm trying to do a POST request using asyncHttpClientand I get a status of 200, but no log from the service that the message was received:

我正在尝试使用asyncHttpClient执行 POST 请求,但状态为 200,但该服务没有收到消息的日志:

private final static ObjectMapper mapper = new ObjectMapper();
private static Request request;

public static void main( String[] args )
{

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();

    String jsonContent="";
    try {
        jsonContent = mapper.writeValueAsString(new Message("diego", "Hello World"));
        System.out.println(jsonContent);
    } catch (IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }

    request = asyncHttpClient.preparePost("http://localhost:8080/Test/").
            setHeader("Content-Type","application/json").
            setHeader("Content-Length", ""+jsonContent.length()).
            setBody(jsonContent).
            build();

    ListenableFuture<Integer> f= null;
    try {
        f = asyncHttpClient.executeRequest(request,
                new AsyncCompletionHandler<Integer>(){

                    @Override
                    public Integer onCompleted(Response response) throws Exception{
                        // Do something with the Response
                        System.out.println(response.getStatusCode());
                        return response.getStatusCode();
                    }

                    @Override
                    public void onThrowable(Throwable t){
                        // Something wrong happened.
                    }
                });

    } catch (IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }

    int statusCode;

    if (f!=null)
    {
        try {
            statusCode = f.get();
        } catch (InterruptedException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    asyncHttpClient.close();

When I use Apache HttpClientthe service logs that the message was received and get a 200 status code:

当我使用Apache HttpClient 时,服务记录收到消息并获得 200 状态代码:

    @SuppressWarnings("deprecation")
    final HttpClient httpClient = new DefaultHttpClient();

    @SuppressWarnings("deprecation")
    StringEntity requestEntity= null;
    try {
        requestEntity = new StringEntity(
            mapper.writeValueAsString(new Message("diego", "Hello World!")),
            ContentType.APPLICATION_JSON);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    } catch(IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }

    HttpPost postMethod = new HttpPost("http://localhost:8080/Test/chat/");
    postMethod.setEntity(requestEntity);

    HttpResponse statusCode= null;
    try {
        statusCode = httpClient.execute(postMethod);
    } catch (IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }

    postMethod.releaseConnection();

    if (statusCode != null)
    {
        System.out.println(statusCode.toString());
    }

Why is asyncHttpClient not working?

为什么 asyncHttpClient 不起作用?

采纳答案by Stephane Landelle

Test is flawed: HttpCompenents test was hitting localhost:8080/Test/chatwhile AsyncHttpClient one was hitting localhost:8080/Test.

测试存在缺陷: HttpCompenents 测试命中,localhost:8080/Test/chat而 AsyncHttpClient测试命中localhost:8080/Test