Отправка полезной нагрузки запроса в rest api java изменение кода без чтения и записи потоков в java

#java

#java

Вопрос:

Я пытаюсь изменить свой код без использования буферизованного метода чтения-записи и потока. может кто-нибудь подсказать мне, как упростить мой код.

Я запускаю этот код в cucumber, и он работает нормально.

 public String creatProduct() throws Throwable {
    String payload = "{"
              ""productName":"Macroon","
              ""productCode":"","
              ""externalRoomId":"","
              ""description":"""
              "}";

    String requestUrl = "www.example.com";
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        System.out.println("Response==>"   jsonString.toString());
        Map<String, String> map = new HashMap<String, String>();
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("Input payload:"   payload);
        map = mapper.readValue(jsonString.toString(), new TypeReference<HashMap<String, String>>() {
        });
        System.out.println("Output Map: "   map);
        map.get("productName");
        assertEquals("Macroon", map.get("productName"));
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
    }
    return jsonString.toString();
}
  

Ответ №1:

Я изменил свой код, и он работает!

  HttpClient httpclient = new HttpClient();
   PostMethod post = new PostMethod("www.example.com");
   post.setRequestEntity(new StringRequestEntity(payload, "application/json", null));    
   httpclient.executeMethod(post);
   String jsonResponse = post.getResponseBodyAsString();
   System.out.println("Response==>" jsonResponse);
   Map<String,String> map1 = new HashMap<String,String>();
   ObjectMapper mapper=new ObjectMapper();  
   System.out.println("Input payload:"  payload);
   map1 = mapper.readValue(jsonResponse, new TypeReference<HashMap<String, String>>(){});
   System.out.println("Output Map: " map1);
   map1.get("message");
   assertEquals("Success",map1.get("message"));