在安卓系统中调用REST(POST)网络服务

3

我正在尝试创建一个web服务并从Android中使用它。GET方法可以正常工作,但我无法调用POST方法。

@Path("/dictionary")
public class DictionaryWebService {

private final static String ID = "id";
private final static String WORD = "palabra";
private final static String DESCRIPTION = "description";

.....  
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Word postNewWord(MultivaluedMap<String, String> newWord) {

    Word dict;


    String id = newWord.getFirst(ID);
    String word = newWord.getFirst(WORD);
    String description = newWord.getFirst(DESCRIPTION);

    dict = new Word(id, word, description);
    dictionary.putNewWord(dict);

    System.out.println("New Word info: " + dict.toString());

    return dict;

    }
}

我的安卓代码如下:

        @Override
        public void onClick(View arg0) {
            System.out.println("onClick!!!");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://10.0.2.2:8080/DictionaryWebService/rest/dictionary/");
            post.setHeader("content-type", "application/json");

            //Construimos el objeto cliente en formato JSON
            JSONObject dato = new JSONObject();



            try {


                dato.put("id", txtId.getText().toString()); 
                dato.put("palabra", txtWord.getText().toString());
                dato.put("description", txtDescription.getText().toString());

                StringEntity entity = new StringEntity(dato.toString());
                post.setEntity(entity);

                HttpResponse resp = httpClient.execute(post);
                String respStr = EntityUtils.toString(resp.getEntity());


                System.out.println("OKAY!");

            .....

        }
    });

我不知道为什么无法执行Web服务,它没有被调用。有什么问题吗?能否有人帮助我?onclick方法在没有任何错误的情况下结束。

谢谢。


你在日志中看到 "OKAY!" 的声明了吗? - Ramesh Sangili
你能否尝试通过调试器运行并逐步执行代码?我感觉捕获块中可能会有异常。 - Ramesh Sangili
是的,我看到了“好的”!我要跟踪代码,并捕获一个通用异常。让我试试!!! - Guille
好的,我执行了代码并进行了调试...一切看起来都很好。没有异常,代码也正常完成了...但是,我在Web服务上有一些痕迹,它们看起来不对劲。有没有什么方法可以像执行GET方法一样从我的浏览器中执行Web服务呢? - Guille
2个回答

2

我使用了你的代码,它工作得很好。我唯一做出的更改是将post header设置为:

post.setHeader("content-type", "application/json; charset=UTF-8");

1

我和你的做法有点不同,但是我在 Stack Overflow 上看到一个类似于你的客户端视角的例子(Http post with parameters not working),它使用了额外的 post.setHeader 调用:

post.setHeader("Accept", "application/json");

这是除了您已经进行的post.setHeader调用之外的另一个步骤。

链接中的示例也是一个很好的短测试,用于检查其他所有内容是否正常工作(健全性检查)。

希望这可以帮到您。


我遇到了同样的问题,但是我得到了这个:HTTP/1.1 415 Tipo de Medio No Soportado,以及两个头文件。这是在执行httpClient.execute(post)后HttpResponse resp的内容。 - Guille
最后,我按照这个教程进行操作,现在它能够正常运行了,尽管我不知道哪一步出了问题。http://avilyne.com/?p=105 - Guille

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接