我正在通过此方法使用RESTfull Web服务:
@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给参数赋予正确的值;
我注意到我可以使用批注@HeaderParam并将标题添加到HttpPost对象。这是正确的方法吗?这样做:
httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("str1", "a value"); httpPost.setHeader("str2", "another value");
在httpPost上使用setEntity方法将不起作用。它仅使用json字符串设置参数str1。像这样使用时:
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,例如:
HttpPostRequest
BasicNameValuePair
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);