Last active
November 14, 2017 17:26
-
-
Save ccrama/03a34e0413935f1063d76168b924d3dc to your computer and use it in GitHub Desktop.
This code gets a Gfycat link from a .gif URL and authenticates if neccessary. This is currently failing with a 400 BadRequest before it even reaches the https://api.gfycat.com/v1/gfycats call
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 me.ccrama.redditslide.util; | |
import android.content.Context; | |
import android.support.annotation.Nullable; | |
import android.text.TextUtils; | |
import com.google.gson.Gson; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonSyntaxException; | |
import java.io.IOException; | |
import java.util.HashMap; | |
import java.util.Map; | |
import me.ccrama.redditslide.Constants; | |
import me.ccrama.redditslide.SecretConstants; | |
import okhttp3.MediaType; | |
import okhttp3.MultipartBody; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import okhttp3.RequestBody; | |
import okhttp3.Response; | |
import okhttp3.ResponseBody; | |
import okio.Buffer; | |
/** | |
* A class that helps with HTTP requests and response parsing. | |
* | |
* Class created by Fernando Barillas on 7/13/16. | |
* Class edited from Slide for Reddit https://github.com/ccrama/Slide/blob/98f5df0eb945fac7d5b8d2e7102cfacfaa754b4c/app/src/main/java/me/ccrama/redditslide/util/HttpUtil.java | |
*/ | |
public class HttpUtil { | |
private static String gfycatToken = ""; | |
private static long expires; | |
public static JsonObject transcodeGfycatGetJsonObject(final Context context, final OkHttpClient client, final Gson gson, | |
final String urlToConvert) { | |
//Check for a valid Gfycat authentication, dirty implementation at the moment because it doesn't refresh, but this code is still not working | |
if(System.currentTimeMillis() > expires || gfycatToken.isEmpty()){ | |
Map<String, String> headers = new HashMap<>(); | |
headers.put("grant_type", "client_credentials"); | |
headers.put("client_id", "2_fEI_VM"); | |
headers.put("content_type", "application/json"); | |
headers.put("client_secret", SecretConstants.getGfycatAPIKey(context)); //Gets private key from a local file on my computer, compiles with the key but it doesn't get pushed to GitHub | |
JsonObject o = getPostJsonObject(client, gson, "https://api.gfycat.com/v1/oauth/token", headers); | |
/* Logging shows these are the request params: | |
Request{method=POST, url=https://api.gfycat.com/v1/oauth/token, tag=null} | |
content_type: application/json | |
grant_type: client_credentials | |
client_secret: secret | |
client_id: 2_fEI_VM*/ | |
if(o.has("expires_in")){ //Hopefully a valid token | |
expires = System.currentTimeMillis() + o.get("expires_in").getAsLong(); | |
gfycatToken = o.get("access_token").getAsString(); | |
} | |
} | |
//Get the converted gfycat | |
Map<String, String> imgurHeadersMap = new HashMap<>(); | |
imgurHeadersMap.put("fetchUrl", urlToConvert); | |
imgurHeadersMap.put("Authorization", gfycatToken); | |
return getJsonObject(client, gson, "https://api.gfycat.com/v1/gfycats", imgurHeadersMap); | |
} | |
//Gets a JSON object with a POST request | |
public static JsonObject getPostJsonObject(final OkHttpClient client, final Gson gson, | |
final String apiUrl, @Nullable final Map<String, String> headersMap) { | |
if (client == null || gson == null || TextUtils.isEmpty(apiUrl)) return null; | |
MediaType MIMEType= MediaType.parse("application/json; charset=utf-8"); | |
RequestBody requestBody = RequestBody.create (MIMEType,"{}"); | |
Request.Builder requestB = new Request.Builder().url(apiUrl); | |
if (headersMap != null && headersMap.size() > 0) { | |
// Add headers to the request if headers are available | |
for (Map.Entry<String, String> entry : headersMap.entrySet()) { | |
requestB.addHeader(entry.getKey(), entry.getValue()); | |
} | |
} | |
Request request= requestB.post(requestBody).build(); | |
try { | |
Response response = client.newCall(request).execute(); | |
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); //Crashes here with a 400 BadRequest | |
ResponseBody responseBody = response.body(); | |
String json = responseBody.string(); | |
responseBody.close(); | |
return gson.fromJson(json, JsonObject.class); | |
} catch (JsonSyntaxException | IOException e) { | |
LogUtil.e(e, "Error " + apiUrl); | |
} | |
return null; | |
} | |
/** | |
* Gets a JsonObject by calling apiUrl and parsing the JSON response String. This method accepts | |
* a Map that can contain custom headers to include in the request. | |
* | |
* @param client The OkHTTP client to use to make the request | |
* @param gson The GSON instance to use to parse the response String | |
* @param apiUrl The URL to call to get the response from | |
* @param headersMap The headers to include in the request. Can be null to not add any headers | |
* @return A JsonObject representation of the API response, null when there was an error or | |
* Exception thrown by the HTTP call | |
*/ | |
public static JsonObject getJsonObject(final OkHttpClient client, final Gson gson, | |
final String apiUrl, @Nullable final Map<String, String> headersMap) { | |
if (client == null || gson == null || TextUtils.isEmpty(apiUrl)) return null; | |
Request.Builder builder = new Request.Builder().url(apiUrl); | |
if (headersMap != null && headersMap.size() > 0) { | |
// Add headers to the request if headers are available | |
for (Map.Entry<String, String> entry : headersMap.entrySet()) { | |
builder.addHeader(entry.getKey(), entry.getValue()); | |
} | |
} | |
Request request = builder.build(); | |
try { | |
Response response = client.newCall(request).execute(); | |
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); | |
ResponseBody responseBody = response.body(); | |
String json = responseBody.string(); | |
responseBody.close(); | |
return gson.fromJson(json, JsonObject.class); | |
} catch (JsonSyntaxException | IOException e) { | |
LogUtil.e(e, "Error " + apiUrl); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment