POST multiple requests using a List of payloads in Java for sending HttpRequest

Viewed 17

I have a payload utility class where I am iterating over a list of payloads (which are in a json file). There is currently one way to identify an individual payload and that is seen below (Product_Div and Product_SubDiv are two individual payloads):

{
  "Product_Div": {
    "reqData": "Product_Div",
    "queryData": [
      {
        "condition": "VendorID",
        "values": [
          "123"
        ]
      }
    ]
  },
  "Product_SubDiv": {
    "reqData": "Product_SubDiv",
    "queryData": [
      {
        "condition": "Product_Div",
        "values": [
          "12345"
        ]
      },
      {
        "condition": "VendorID",
        "values": [
          "123"
        ]
      }
    ]
  }
}

I have a payload utility as below to convert json payloads to a string in order to send in the request body for my http requests (using org.json.simple):

public class PayloadUtil {

    public static String getPayload(String filePathAndName, String payloadString) {
        JSONParser jsonParser = new JSONParser();

        try (FileReader reader = new FileReader(filePathAndName)) {
            //Read JSON file
            JSONObject obj = (JSONObject) jsonParser.parse(reader);

            String s = obj.toJSONString();

//            JSONObject allValues = (JSONObject) obj.get("Product_Div);
            JSONObject allValues = (JSONObject) obj.get(payloadString);

            //System.out.println("JIRA REQ Details : "+allValues.toJSONString());
            //Iterate over employee array
            return allValues.toJSONString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}

Now that I have converted the json payload to string, I want to be able to loop through each payload and send the request for each payload. Currently I only have the String hardcoded which is not very efficient. I have my methods below where postRequest() is used to build the httprequest and get the response generically with inputs as url and payload, and postRequestWithPayload() should send each request and get a response for the specific payload:

private HttpResponse<String> postRequest(String url, String payload) {
    try {
        HttpRequest request2 = HttpRequest.newBuilder()
                .uri(new URI(url))
                .setHeader("Content-Type", "application/json")
                .setHeader("Authorization", "Bearer " + bearerToken)
                .setHeader("Cookie", "amlbcookie=" + cookie1 + "; " + "dvgwauthcookie=" + cookie2)
                .POST(HttpRequest.BodyPublishers.ofString(payload))
                .build();
        httpResponse = client().send(request2, HttpResponse.BodyHandlers.ofString());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return httpResponse;
}

private void postRequestWithPayload() {
    try {
        String productDivPayload = PayloadUtil.getPayload(masterPostJsonFile, "Product_Div");
        String productSubDivPayload = PayloadUtil.getPayload(masterPostJsonFile, "Product_SubDiv");
        System.out.println("Product_DIv is " + productDivPayload + " Product Subdiv is " + productSubDivPayload);
        httpResponse = postRequest(RestAssured.baseURI + masterProdHieEndPt, productSubDivPayload);
        //System.out.println("Status code is " + httpResponse.statusCode() + " for master API payload " + productSubDivPayload);
        //System.out.println("Response body is " + httpResponse.body() + " for master API payload " + productSubDivPayload);
    } catch (Exception e) {
        Reporter.log("ERROR: Issue executing post request: " + e.getMessage());
    }
}

How can I make this more efficient without hardcoding the payload key and loop through the payload list and send the requests and get the response?

0 Answers
Related