无法在Java中发送正确的POST请求(Android Studio) [英] Can't send a correct POST request in Java (Android Studio)

查看:264
本文介绍了无法在Java中发送正确的POST请求(Android Studio)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个用于提问/回答问题的应用。
当我提问时我的POST请求有问题。

I'm creating an app for asking/answering questions. I have a problem with POST request when I ask questions.

我试图在终端中使用这样的东西

I've tried to use something like this in terminal

curl -H "Content-Type: application/json" -d '{"firstName":"Chris", "lastName": "Chang", "email": "support@mlab.com"}' http://your-app-name.herokuapp.com/contacts

并且效果很好。

但是当我尝试在AndroidStudio中发送POST请求时,我的参数(例如姓名,姓氏,电子邮件等)赢了发送。
我试图使用 https://github.com/kevinsawicki/http-request 。请求是发送的(我知道,因为它显示了请求的日期),但没有任何参数。

But when I try to send a POST request in AndroidStudio my parameters (such as name, lastname, email and etc) won't send. I tried to use https://github.com/kevinsawicki/http-request. The request is send (I know that because it shows the date of the request) but without any parameters.

我的代码中应该更改哪些内容才能正常工作?

What should be changed in my code so it would work correctly?

Map<String, String> data = new HashMap<String, String>();
data.put("firstName", "Gena");
data.put("lastName", "Bukin");
if (HttpRequest.post("https://safe-citadel-91138.herokuapp.com/questions").form(data).created())
System.out.println("User was created");


推荐答案

我刚刚尝试创建用户并且它工作正常。您可以刷新已共享的链接以检查创建的用户。

I have just tried to create an User and it worked. You can refresh the link u have shared to check the created User.

这就是我的尝试

String endPoint= "https://safe-citadel-91138.herokuapp.com/questions";
        try {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost post = new HttpPost(endPoint);
            post.addHeader("Content-Type", "application/json");
            JSONObject obj = new JSONObject();

            obj.put("firstName", "TESTF");
            obj.put("lastName", "TESTL");
            obj.put("email", "support@mlab.com");

            StringEntity entity = new StringEntity(obj.toString()); 
            post.setEntity(entity);
            HttpResponse response = httpClient.execute(post);
}catch (Exception e){

        }

UPDATE

BTW我使用了来自这个链接

BTW I have used json jar from this link

这篇关于无法在Java中发送正确的POST请求(Android Studio)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆