如何在 HttpPost 中使用参数 [英] How to use parameters with HttpPost

查看:46
本文介绍了如何在 HttpPost 中使用参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过这种方法使用 RESTfull 网络服务:

I am using a RESTfull webservice with this methode:

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(String str1, String str2){
System.out.println("value 1 = " + str1);
System.out.println("value 2 = " + str2);
}

在我的 Android 应用中,我想调用这个方法.如何使用 org.apache.http.client.methods.HttpPost 为参数提供正确的值;

In my Android app I want to call this method. How do I give the correct values to the parameters using org.apache.http.client.methods.HttpPost;

我注意到我可以使用注释@HeaderParam 并简单地向 HttpPost 对象添加标头.这是正确的方法吗?这样做:

I have noticed that I can use the annotation @HeaderParam and simply add headers to the HttpPost object. Is this the correct way? Doing it like:

httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("str1", "a value");
httpPost.setHeader("str2", "another value");

在 httpPost 上使用 setEntity 方法不起作用.它仅使用 json 字符串设置参数 str1.当使用它时:

Using the setEntity methode on httpPost won't work. It only sets the parameter str1 with the json string. When using it like:

JSONObject json = new JSONObject();
json.put("str1", "a value");
json.put("str2", "another value");
HttpEntity e = new StringEntity(json.toString());
httpPost.setEntity(e);
//server output: value 1 = {"str1":"a value","str2":"another value"} 

推荐答案

要为 HttpPostRequest 设置参数,您可以使用 BasicNameValuePair,如下所示:

To set parameters to your HttpPostRequest you can use BasicNameValuePair, something like this :

    HttpClient httpclient;
    HttpPost httpPost;
    ArrayList<NameValuePair> postParameters;
    httpclient = new DefaultHttpClient();
    httpPost = new HttpPost("your login link");


    postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));

    HttpResponse response = httpclient.execute(httpPost);

这篇关于如何在 HttpPost 中使用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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