如何使用HttpPost参数

我正在使用这种方法使用RESTfull webservice:

@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方法将不起作用。 它只用jsonstring设置参数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 ,像这样:

  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); 

如果你想传递一些http参数并发送一个json请求,你也可以使用这种方法:

(注意:我已经添加了一些额外的代码,只是为了帮助其他未来的读者)

 public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException { //add the http parameters you wish to pass List<NameValuePair> postParameters = new ArrayList<>(); postParameters.add(new BasicNameValuePair("param1", "param1_value")); postParameters.add(new BasicNameValuePair("param2", "param2_value")); //Build the server URI together with the parameters you wish to pass URIBuilder uriBuilder = new URIBuilder("http://google.ug"); uriBuilder.addParameters(postParameters); HttpPost postRequest = new HttpPost(uriBuilder.build()); postRequest.setHeader("Content-Type", "application/json"); //this is your JSON string you are sending as a request String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} "; //pass the json string request in the entity HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8")); postRequest.setEntity(entity); //create a socketfactory in order to use an http connection manager PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainSocketFactory) .build(); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry); connManager.setMaxTotal(20); connManager.setDefaultMaxPerRoute(20); RequestConfig defaultRequestConfig = RequestConfig.custom() .setSocketTimeout(HttpClientPool.connTimeout) .setConnectTimeout(HttpClientPool.connTimeout) .setConnectionRequestTimeout(HttpClientPool.readTimeout) .build(); // Build the http client. CloseableHttpClient httpclient = HttpClients.custom() .setConnectionManager(connManager) .setDefaultRequestConfig(defaultRequestConfig) .build(); CloseableHttpResponse response = httpclient.execute(postRequest); //Read the response String responseString = ""; int statusCode = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); HttpEntity responseHttpEntity = response.getEntity(); InputStream content = responseHttpEntity.getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String line; while ((line = buffer.readLine()) != null) { responseString += line; } //release all resources held by the responseHttpEntity EntityUtils.consume(responseHttpEntity); //close the stream response.close(); // Close the connection manager. connManager.close(); } 

一般来说,HTTP POST假定正文的内容包含一系列由HTML侧的表单创build(最常见)的键/值对。 您不要使用setHeader设置值,因为这不会将它们放在内容主体中。

因此,在第二次testing中,您遇到的问题是您的客户端没有创build多个键/值对,只创build了一个,并且默认映射到方法中的第一个参数。

有几个选项可以使用。 首先,您可以将您的方法更改为仅接受一个input参数,然后像在第二个testing中一样传入JSONstring。 一旦进入方法,您然后parsingJSONstring到一个对象,允许访问字段。

另一种select是定义一个表示inputtypes的字段的类,并将其作为唯一的input参数。 例如

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

根据你使用的REST框架,它应该为你处理JSON的反序列化。

最后一个选项是构build一个看起来像这样的POST主体:

 str1=value1&str2=value2 

然后添加一些额外的注释到您的服务器方法:

 public void create(@QueryParam("str1") String str1, @QueryParam("str2") String str2) 

@QueryParam不关心该字段是在表单发布中还是在URL中(如GET查询)。

如果你想继续在input上使用单独的参数,那么这个键将生成客户端请求,以便在URL(GET)或POST主体中提供命名查询参数。