【问题标题】:Passing XML as body in PUT request through JAVAPassing XML as body in PUT request through JAVA
【发布时间】:2022-12-01 19:09:32
【问题描述】:

I want to hit a PUT API and pass XML as body of the API in JAVA. Can someone please tell me how to do it.

For passing JSON as Body of the API in JAVA I use

 obj = parser.parse(new FileReader("file Path"));
        jsonObject = (JSONObject) obj;
        String jsonString = jsonObject.toJSONString();
        Map<String, String> body = new ObjectMapper().readValue(jsonString, HashMap.class);
        response = RestAssuredExtension.PostOpsWithBody(url, body);

I know how to call the PUT API but not how to pass the xml as body

【问题讨论】:

    标签: java xml


    【解决方案1】:

    First of all your code parses JSON into instance of Mapclass and then attempts to send it into your API. Also method name suggests that it is a POST method and not PUT. So what is it? Do you need to use POST or PUT method and what body format is expected by that method? In any case.

    In any case here are some options on how you can do this:

    1. If you work with Spring boot There are 2 http clients provided by Spring boot. Here is the article that compares them: Spring WebClient vs. RestTemplate

    2. Apache Http Client is very popular 3d party Http client.

    3. OK Http client is another popular one

    4. And my favorite is far less known but very simple in use Http client from MgntUtils Open source library written and maintained by me. In this client there is simply a method that allows you to send any String (or byte array) as a parameter to your API endpoint and it will be sent as a body. Your code may look as something like this:

      public static void sendHttpRequest() {
      HttpClient httpClient = new HttpClient();
      try {
          httpClient.setContentType("application/json");
          String url = "http://myApiAddress.coom/myMethod";
          String jsonData = "{"testKey": "Test Value"}";
          httpClient.setRequestHeader("Content-Length", "" + jsonData.length());
          String result = httpClient.sendHttpRequest(url, HttpClient.HttpMethod.POST, jsonData);
          System.out.println(result);
      } catch (Exception e) {
          System.out.println(TextUtils.getStacktrace(e, "com.mgnt.stam."));
      }
      

      }

      Here is Javadoc for sendHttpRequest method. As for the MgntUtils library you can get it as Maven artifact here or on Github (with source code and Javadoc included)

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      相关资源
      最近更新 更多