Making post request fos asynch job



I am trying to make a Http POST request for

And when I try to do it with java I get 401 or MalformedURLException but when I try it with Postman it works just fine.

Here is my code for the POST request

public String executePost(String oauth_signature, List ids) throws Exception {
URL url = new URL(reportData.getUriForPostJobs());my url here is

      HttpURLConnection connection = null;
      StringBuilder response = null;

     Map<String, String> parameters = new LinkedHashMap<>();
     parameters.put("granularity", "DAY");
     parameters.put("placement", "ALL_ON_TWITTER");
     parameters.put("start_time", "2018-09-05");
     parameters.put("end_time", "2018-09-11");
     parameters.put("entity", "CAMPAIGN");
     parameters.put("entity_ids", String.join(",", ids));
     parameters.put("metric_groups", "ENGAGEMENT");

     //Adding parameters
     StringBuilder postData = new StringBuilder();
     for (Map.Entry<String, String> param : parameters.entrySet()) {
         if (postData.length() != 0)
         postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
         postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
     byte[] postDataBytes = postData.toString().getBytes("UTF-8");

     try {
         String readLine = null;
         connection = (HttpURLConnection) url.openConnection();
         connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
         connection.setRequestProperty("Authorization", oauth_signature);

         int responseCode = connection.getResponseCode();

         BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
         response = new StringBuilder();
         while ((readLine = bufferedReader.readLine()) != null) {
     } catch (IOException e) {
         throw new MalformedURLException(e.getMessage());
     } finally {
         if (connection != null) {
     return response.toString();

I have also tried to do a StringBuilder to append all the url and the parameters like this StringBuilder uri = new StringBuilder().append(reportData.getUriForPostJobs()).append("?").append(postDataBytes);

But nothing seems to work.



I believe this is not really an “API” related question but general Java code question…
But here’s what you may want to read:

You should escape parameters in general.


Well I my code working by putting the whole url address (including parameters) when creating the signature and when doing the POST request!