Java Requires Chilkat v11.0.0+
Java
SendGrid: Report daily requests, deliveries, bounces, and blocks
See more SendGrid Examples
Retrieve seven completed UTC dates and print one row per date. The counts are account-level aggregates; a day’s delivered count does not identify which messages sent that day were delivered.
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonArray;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
boolean success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false;
Http http = new Http();
http.setRequireSslCertVerify(true);
// Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
http.setAuthToken("SENDGRID_API_KEY");
HttpResponse resp = new HttpResponse();
DateTime day = new DateTime();
day.setFromCurrentSystemTime();
day.addDays(-1);
http.setUrlVar("end", day.getAsIso8601("YYYY-MM-DD", false));
day.addDays(-6);
http.setUrlVar("start", day.getAsIso8601("YYYY-MM-DD", false));
try {
http.httpNoBody("GET", "https://api.sendgrid.com/v3/stats?start_date={$start}&end_date={$end}&aggregated_by=day", resp);
} catch (ChilkatException e) {
if (resp.getStatusCode() == 0) {
System.out.println(e.getLastErrorText());
} else {
System.out.println("HTTP " + resp.getStatusCode() + ": " + resp.getBodyStr());
}
return;
}
if (resp.getStatusCode() != 200) {
System.out.println("HTTP " + resp.getStatusCode() + ": " + resp.getBodyStr());
return;
}
JsonArray days = new JsonArray();
try {
days.load(resp.getBodyStr());
} catch (ChilkatException e) {
System.out.println("Unexpected response: expected JSON.");
return;
}
System.out.println("Date,Requests,Delivered,Bounces,Blocks");
JsonObject row = new JsonObject();
int i = 0;
while (i < days.getSize()) {
days.objectAt2(i, row);
System.out.println(row.stringOf("date") + "," + row.intOf("stats[0].metrics.requests") + "," + row.intOf("stats[0].metrics.delivered") + "," + row.intOf("stats[0].metrics.bounces") + "," + row.intOf("stats[0].metrics.blocks"));
i = i + 1;
}
}
}