Last active
April 14, 2024 12:20
-
-
Save deepanshumehtaa/e423fccbc28370c1793f35aae134d233 to your computer and use it in GitHub Desktop.
APIClient Java
This file contains hidden or 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 org.example.ApiC; | |
import java.io.IOException; | |
import java.util.HashMap; | |
import java.util.Map; | |
//import org.slf4j.Logger; | |
import java.util.Objects; | |
import okhttp3.MediaType; | |
import okhttp3.OkHttpClient; | |
import okhttp3.Request; | |
import okhttp3.RequestBody; | |
import okhttp3.Response; | |
import org.json.JSONArray; | |
import org.json.JSONObject; | |
public class APIClient { | |
private static String url = ""; | |
private Object response; | |
private final String HMethod; | |
public APIClient(String url, HMethods hMethod) { | |
APIClient.url = url; | |
HMethod = hMethod.toString(); | |
} | |
// Use this only | |
public static Object makeCall(Request req, boolean many) throws IOException { | |
OkHttpClient client = new OkHttpClient(); | |
try (Response response = client.newCall(req).execute()) { | |
if (!response.isSuccessful()) { | |
throw new IOException("API call failed: " + response); | |
} | |
String responseBody = response.body().string(); | |
if(many){ | |
return new JSONArray(responseBody); | |
} else { | |
return new JSONObject(responseBody); | |
} | |
} | |
} // makeCall ends | |
public Object makeGET(boolean many) throws IOException { | |
/* | |
* Object res = (Object) new APIClient(url, HMethods.GET).makeGET(true); | |
* JSONArray res = (JSONArray) new APIClient(url, HMethods.GET).makeGET(true); | |
*/ | |
Request request; | |
request = new Request.Builder() | |
.url(APIClient.url) | |
.method("GET", null) | |
.build(); | |
return APIClient.makeCall(request, many); | |
} // makeGET ends | |
public Object makePOST(boolean many, Map<Object, Object> reqBody) throws IOException { | |
Request request; | |
RequestBody reqB; | |
if (reqBody != null) { | |
JSONObject jObject = new JSONObject(reqBody); | |
reqB = RequestBody.create( | |
jObject.toString(), | |
MediaType.get("application/json; charset=utf-8") | |
); | |
} else { | |
reqB = null; | |
} | |
request = new Request.Builder() | |
.url(APIClient.url) | |
.method("POST", reqB) | |
.build(); | |
return APIClient.makeCall(request, many); | |
} // makePOST ends | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment