programing

HttpPost에서 매개 변수를 사용하는 방법

lastcode 2023. 3. 18. 08:41
반응형

HttpPost에서 매개 변수를 사용하는 방법

다음 메토드에서 RESTfull 웹 서비스를 사용하고 있습니다.

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

제 안드로이드 앱에서는 이 메서드를 부르고 싶습니다.org.apache.http.client.methods를 사용하여 파라미터에 올바른 값을 지정하려면 어떻게 해야 합니까?Http Post;

@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를 사용하여 값을 설정하지 않으면 콘텐츠 본문에 값이 배치되지 않습니다.

두 번째 테스트에서는 클라이언트가 여러 개의 키/값 쌍을 만들지 않고 하나의 키/값 쌍만 만들고 기본적으로는 메서드의 첫 번째 인수에 매핑된다는 문제가 발생합니다.

몇 가지 옵션을 사용할 수 있습니다.먼저 입력 파라미터를 1개만 받아들이도록 메서드를 변경한 후 두 번째 테스트에서처럼 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 본문 중 하나에서 이름 있는 쿼리 파라미터를 제공하는 클라이언트 요청을 생성하는 것이 키입니다.

언급URL : https://stackoverflow.com/questions/8120220/how-to-use-parameters-with-httppost

반응형