Created
May 17, 2016 11:30
-
-
Save FodT/ad4a13d1cb7207d0734df0b50b4b7e72 to your computer and use it in GitHub Desktop.
Using Unirest.io to make T1 API calls in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.mycompany.app; | |
import com.mashape.unirest.http.HttpResponse; | |
import com.mashape.unirest.http.Unirest; | |
import com.mashape.unirest.http.exceptions.UnirestException; | |
import org.json.JSONArray; | |
import java.util.HashMap; | |
import java.util.Map; | |
/** | |
* Hello, t1! | |
* demonstrate using Unirest.io to make some t1 API calls | |
*/ | |
public class App { | |
static String APIBASE = "https://api.mediamath.com/api/v2.0/"; | |
static String JSON = "application/vnd.mediamath.v1+json"; | |
public static void main(String[] args) throws UnirestException { | |
// set the default accept header, this gets sent with each request. | |
// our json return format is much nicer than XML! | |
Unirest.setDefaultHeader("Accept", JSON); | |
//query the current api version | |
String versionBody = Unirest | |
.get(APIBASE + "version") | |
.asString().getBody(); | |
System.out.println(versionBody); | |
Map<String, Object> loginFields = new HashMap<>(); | |
Map<String, String> env = System.getenv(); | |
//log in | |
loginFields.put("user", env.getOrDefault("T1_API_USERNAME", "")); | |
loginFields.put("password", env.getOrDefault("T1_API_PASSWORD", "")); | |
loginFields.put("api_key", env.getOrDefault("T1_API_KEY", "")); | |
HttpResponse<String> jsonResponse = Unirest | |
.post(APIBASE + "login") | |
.fields(loginFields) | |
.asString(); | |
System.out.println(jsonResponse.getBody()); | |
//get the session; yay unirest persists cookies! | |
jsonResponse = Unirest | |
.get(APIBASE + "session") | |
.asString(); | |
System.out.println(jsonResponse.getBody()); | |
// get the first 10 campaigns | |
JSONArray result = Unirest | |
.get(APIBASE + "campaigns") | |
.queryString("page_limit", 10) | |
.asJson().getBody().getObject().getJSONArray("data"); | |
for (int i = 0; i < result.length(); i++) { | |
System.out.println(result.getJSONObject(i).getString("name")); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment