簡體   English   中英

如何在 HttpPost 中使用參數

[英]How to use parameters with HttpPost

我正在使用帶有此方法的 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 ,如下所示:

    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 端的表單創建。 您不使用 setHeader 設置值,因為這不會將它們放置在內容正文中。

因此,對於您的第二個測試,您在這里遇到的問題是您的客戶端沒有創建多個鍵/值對,它只創建了一個並且默認映射到您的方法中的第一個參數。

您可以使用幾個選項。 首先,您可以將方法更改為僅接受一個輸入參數,然后像在第二個測試中一樣傳入一個 JSON 字符串。 一旦進入該方法,您就可以將 JSON 字符串解析為允許訪問字段的對象。

另一種選擇是定義一個表示輸入類型字段的類,並使其成為唯一的輸入參數。 例如

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 的反序列化。

最后一個選項是構建一個 POST 主體,如下所示:

str1=value1&str2=value2

然后向您的服務器方法添加一些額外的注釋:

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

@QueryParam 不關心該字段是在表單帖子中還是在 URL 中(如 GET 查詢)。

如果您想繼續在輸入上使用單個參數,那么關鍵是生成客戶端請求以在 URL(對於 GET)或 POST 正文中提供命名查詢參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM