Java
Chilkat2 Java
Create a New GMail Label
See more GMail REST API Examples
Demonstrates how to create a new GMail label.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Http http = new Http();
http.setAuthToken("GMAIL-ACCESS-TOKEN");
String userId = "me";
http.setUrlVar("userId", userId);
// Create the JSON to be sent in the HTTP request body.
// The name of the new label is "questions".
JsonObject json = new JsonObject();
json.updateString("name", "questions");
json.updateString("labelListVisibility", "labelShow");
json.updateString("messageListVisibility", "show");
json.setEmitCompact(false);
System.out.println(json.emit());
// The JSON contains this:
// {
// "name": "questions",
// "labelListVisibility": "labelShow",
// "messageListVisibility": "show"
// }
String url = "https://www.googleapis.com/gmail/v1/users/{$userId}/labels";
HttpResponse resp = new HttpResponse();
try {
http.httpJson("POST", url, json, "application/json", resp);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
System.out.println("status = " + resp.getStatusCode());
// A 200 response status indicate success.
if (resp.getStatusCode() != 200) {
System.out.println(resp.getBodyStr());
System.out.println("Failed.");
return;
}
// A successful repsonse contains JSON that looks like this:
// {
// "id": "Label_43",
// "name": "questions",
// "messageListVisibility": "show",
// "labelListVisibility": "labelShow"
// }
System.out.println("response body:");
System.out.println(resp.getBodyStr());
System.out.println("GMail label created!");
}
}