1
votes

Comment passer un paramètre complexe à une requête POST à ​​l'aide du client HTTP Apache?

J'essaie d'envoyer une requête POST avec un corps comme celui-ci

static final String HOST = "https://somehost.com";

  public String sendPost(String method,
      Map<String, String> methodProperties) throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(HOST);

    List<NameValuePair> urlParameters = new ArrayList<>();
    urlParameters.add(new BasicNameValuePair("method", method));

    List<NameValuePair> methodPropertiesList = methodProperties.entrySet().stream()
                .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList());

    // ??? urlParameters.add(new BasicNameValuePair("methodProperties", methodPropertiesList));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(post)) {

      return EntityUtils.toString(response.getEntity());
    }
  }

Voici mon code

{
  "method": "getAreas",
  "methodProperties": {
      "prop1" : "value1",
      "prop2" : "value2",
   }
}

Mais le constructeur de BasicNameValuePair applique (String, String) . J'ai donc besoin d'une autre classe à la place.

Existe-t-il un moyen d'ajouter methodPropertiesList à urlParameters?


0 commentaires

3 Réponses :


3
votes

votre demande ressemble à une structure json alors publiez des données comme ci-dessous:

 class pojo1{
   String method;
   Map<String,String> methodProperties;
 }

String postUrl = "www.site.com";// put in your url
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson()    converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse  response = httpClient.execute(post);

ref: HTTP POST utilisant JSON en Java


0 commentaires

0
votes

Il existe une approche bien connue de ce problème. Dans la plupart des cas, vous créerez votre propre objet décrivant la chose que vous souhaitez envoyer dans HttpPost. Vous aurez donc quelque chose comme:

static final String HOST = "https://somehost.com";

  public String sendPost(String method,
      Map<String, String> methodProperties) throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(HOST);
    MyResource resource = new MyResource();
    resource.setMethod(method);
    MyNestedResource nestedResource = new MyNestedResource();
    nestedResource.setMethodProperties(methodProperties);
    resource.setNestedResourceMethodProperties(nestedResource);

    StringEntity strEntity = new StringEntity(gson.toJson(resource));
    post.setEntity(strEntity);

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(post)) {

      return EntityUtils.toString(response.getEntity());
    }
  }

Et c'est généralement ainsi que vous abordez des objets json plus complexes avec une structure imbriquée. Vous devez créer des classes pour les ressources que vous souhaitez envoyer (dans votre exemple, il peut s'agir d'une classe et d'utiliser une carte, mais généralement vous créez également une classe pour l'objet imbriqué s'il a une structure spécifique). Pour vous familiariser avec le tableau d'ensemble, mieux couvrez ce tutoriel: https: //www.baeldung .com / objet-dynamique-mappage-jackson


2 commentaires

Je comprends le chemin de vos pensées, mais setEntity a une signature comme celle-ci (entité org.apache.http.HttpEntity) . Pour implémenter HttpEntity , je dois implémenter un tas de méthodes


oui désolé vous pouvez utiliser ceci: StringEntity strEntity = new StringEntity (gson.toJson (resource)); Je modifierai également ma réponse.



0
votes

En utilisant la réponse de Sushil Mittal , voici ma solution

  class Params {

    String method;   
    Map<String, String> methodProperties;

    public Params(String method, Map<String, String> methodProperties) {
      this.method = method;
      this.methodProperties = methodProperties;
    }

    //getters
  }

static final String HOST = "https://somehost.com";

  public String sendPost(String method, Map<String, String> methodProperties) throws ClientProtocolException, IOException {

    HttpPost post = new HttpPost(HOST);  
    Gson gson = new Gson();

    Params params = new Params(method, methodProperties);
    StringEntity entity = new StringEntity(gson.toJson(params));   
    post.setEntity(entity);

    try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(post)) {

      return EntityUtils.toString(response.getEntity());
    }
  }


0 commentaires