-
Notifications
You must be signed in to change notification settings - Fork 0
CoHTTP
CoHTTP allows sending GET and POST requests to an HTTP server.
There is not really much setup other than importing com.coalesce.http.CoHTTP your class does not have to be a CoPlugin or CoModule to use CoHTTP.
The sendGet() method accepts two parameters; The first parameter is the URL to the http server, and the second is the useragent. Make sure to follow the notes
In this example, we GET from TheArtex's public API to view the current announcements on the website.
package com.coalesce.http;
import com.coalesce.http.CoHTTP;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
public class ExampleCoHTTP {
public ExampleCoHTTP() {
// Create GET request
ListenableFuture<String> out = CoHTTP.sendGet("https://www.theartex.net/cloud/api/?sec=announcements", "Example-CoHTTP/1.0");
// Add a listener to wait for response
out.addListener(() -> {
try {
// Get response with `out.get()`
String response = out.get();
// Do what you want with response
// In this case the response is JSON and you can go from here
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}, Runnable::run);
}
}The sendPost() method is a little more complicated than sendGet() as accepts three parameters; The first parameter is the URL to the http server, the second is the post parametes, and the third is the useragent. Make sure to follow the notes
In this example, we POST to TheArtex's public API to login to their website.
package com.coalesce.http;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
public class ExampleCoHTTP {
public ExampleCoHTTP(String username, String hashedPassword) {
// Create POST parameters
HashMap<String, String> postParametets = new HashMap<>();
postParametets.put("sec", "login");
postParametets.put("username", username);
postParametets.put("password", hashedPassword);
// Create POST request
ListenableFuture<String> out = CoHTTP.sendPost("https://www.theartex.net/cloud/api/", postParametets, "Example-CoHTTP/1.0");
// Add a listener to wait for response
out.addListener(() -> {
try {
// Get response with `out.get()`
String response = out.get();
// Do what you want with response
// In this case the response is JSON and you can go from here
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}, Runnable::run);
}
}- Urls should follow the format in java.net.URL
- User agents do not have a specific format but it is best to use
Application/version(ie.Chrome/57.0)