use of com.github.kevinsawicki.http.HttpRequest in project here-android-sdk-examples by heremaps.
the class MapFragmentView method makeRequest.
void makeRequest(GeoCoordinate[] list, final Callback callback) {
final HttpRequest httpRequest = HttpRequest.post(URL_UPLOAD_ROUTE + "?app_id=" + m_appId + "&app_code=" + m_appToken + "&map_name=" + m_overlayName + "&storage=readonly");
final StringBuilder overlaySpec = new StringBuilder();
overlaySpec.append("[");
StringBuilder pathStr = new StringBuilder();
pathStr.append("[");
for (GeoCoordinate geoCoordinate : list) {
pathStr.append("[").append(geoCoordinate.getLatitude()).append(",").append(geoCoordinate.getLongitude()).append("]").append(",");
}
pathStr.deleteCharAt(pathStr.length() - 1);
pathStr.append("]");
String shape = "{\"op\":\"create\",\"shape\":" + pathStr + "}";
overlaySpec.append(shape).append(",");
overlaySpec.deleteCharAt(overlaySpec.length() - 1);
overlaySpec.append("]");
new Thread(new Runnable() {
@Override
public void run() {
if (MapFragmentView.this.m_activity.isDestroyed()) {
return;
}
httpRequest.part("overlay_spec", overlaySpec.toString());
if (httpRequest.created()) {
callback.onResponse(httpRequest.body());
} else {
String message;
try {
message = "Code:" + httpRequest.code() + ", " + httpRequest.body();
} catch (HttpRequest.HttpRequestException e) {
message = e.getMessage();
}
callback.onResponse(message);
}
}
}).start();
}
use of com.github.kevinsawicki.http.HttpRequest in project DiscordSRV by DiscordSRV.
the class DebugUtil method uploadToBin.
private static String uploadToBin(String binHost, int aesBits, List<Map<String, String>> files, String description) {
String key = RandomStringUtils.randomAlphanumeric(aesBits == 256 ? 32 : 16);
byte[] keyBytes = key.getBytes();
// decode to bytes, encrypt, base64
List<Map<String, String>> encryptedFiles = new ArrayList<>();
for (Map<String, String> file : files) {
Map<String, String> encryptedFile = new HashMap<>(file);
encryptedFile.entrySet().removeIf(entry -> StringUtils.isBlank(entry.getValue()));
encryptedFile.replaceAll((k, v) -> b64(encrypt(keyBytes, file.get(k))));
encryptedFiles.add(encryptedFile);
}
Map<String, Object> payload = new HashMap<>();
payload.put("description", b64(encrypt(keyBytes, description)));
payload.put("expiration", TimeUnit.DAYS.toMinutes(7));
payload.put("files", encryptedFiles);
HttpRequest request = HttpRequest.post(binHost + "/v1/post").userAgent("DiscordSRV " + DiscordSRV.version).send(GSON.toJson(payload));
if (request.code() == 200) {
Map json = GSON.fromJson(request.body(), Map.class);
if (json.get("status").equals("ok")) {
return binHost + "/" + json.get("bin") + "#" + key;
} else {
String reason = "";
if (json.containsKey("error")) {
Map error = (Map) json.get("error");
reason = ": " + error.get("type") + " " + error.get("message");
}
throw new RuntimeException("Bin upload status wasn't ok" + reason);
}
} else {
throw new RuntimeException("Got bad HTTP status from Bin: " + request.code());
}
}
use of com.github.kevinsawicki.http.HttpRequest in project DiscordSRV by DiscordSRV.
the class WebhookUtil method deliverMessage.
private static void deliverMessage(TextChannel channel, String webhookName, String webhookAvatarUrl, String message, MessageEmbed embed, boolean allowSecondAttempt) {
if (channel == null)
return;
String webhookUrl = getWebhookUrlToUseForChannel(channel);
if (webhookUrl == null)
return;
Bukkit.getScheduler().runTaskAsynchronously(DiscordSRV.getPlugin(), () -> {
try {
JSONObject jsonObject = new JSONObject();
// workaround for a Discord block for using 'Clyde' in usernames
jsonObject.put("username", webhookName.replaceAll("((?i)c)l((?i)yde)", "$1I$2").replaceAll("(?i)(clyd)e", "$13"));
jsonObject.put("avatar_url", webhookAvatarUrl);
if (StringUtils.isNotBlank(message))
jsonObject.put("content", message);
if (embed != null) {
JSONArray jsonArray = new JSONArray();
jsonArray.put(embed.toData().toMap());
jsonObject.put("embeds", jsonArray);
}
JSONObject allowedMentions = new JSONObject();
Set<String> parse = MessageAction.getDefaultMentions().stream().filter(Objects::nonNull).map(Message.MentionType::getParseKey).collect(Collectors.toSet());
allowedMentions.put("parse", parse);
jsonObject.put("allowed_mentions", allowedMentions);
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Sending webhook payload: " + jsonObject);
HttpRequest request = HttpRequest.post(webhookUrl).header("Content-Type", "application/json").userAgent("DiscordSRV/" + DiscordSRV.getPlugin().getDescription().getVersion()).send(jsonObject.toString());
int status = request.code();
if (status == 404) {
// 404 = Invalid Webhook (most likely to have been deleted)
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Webhook delivery returned 404, marking webhooks URLs as invalid to let them regenerate" + (allowSecondAttempt ? " & trying again" : ""));
// tell it to get rid of the urls & get new ones
invalidWebhookUrlForChannel(channel);
if (allowSecondAttempt)
deliverMessage(channel, webhookName, webhookAvatarUrl, message, embed, false);
return;
}
String body = request.body();
try {
JSONObject jsonObj = new JSONObject(body);
if (jsonObj.has("code")) {
// 10015 = unknown webhook, https://discord.com/developers/docs/topics/opcodes-and-status-codes#json-json-error-codes
if (jsonObj.getInt("code") == 10015) {
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Webhook delivery returned 10015 (Unknown Webhook), marking webhooks url's as invalid to let them regenerate" + (allowSecondAttempt ? " & trying again" : ""));
// tell it to get rid of the urls & get new ones
invalidWebhookUrlForChannel(channel);
if (allowSecondAttempt)
deliverMessage(channel, webhookName, webhookAvatarUrl, message, embed, false);
return;
}
}
} catch (Throwable ignored) {
}
if (status == 204) {
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Received API response for webhook message delivery: " + status);
} else {
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, "Received unexpected API response for webhook message delivery: " + status + " for request: " + jsonObject.toString() + ", response: " + body);
}
} catch (Exception e) {
DiscordSRV.error("Failed to deliver webhook message to Discord: " + e.getMessage());
DiscordSRV.debug(Debug.MINECRAFT_TO_DISCORD, e);
}
});
}
use of com.github.kevinsawicki.http.HttpRequest in project sonarqube by SonarSource.
the class WebTest method request.
PageStats request(String path) {
String url = orchestrator.getServer().getUrl() + path;
// warm-up
for (int i = 0; i < 5; i++) {
newRequest(url).code();
}
long targetDuration = Long.MAX_VALUE;
long targetSize = 0L;
for (int i = 0; i < 10; i++) {
HttpRequest request = newRequest(url);
long start = System.currentTimeMillis();
if (request.ok()) {
long duration = System.currentTimeMillis() - start;
int size = request.body().length();
if (duration < targetDuration) {
targetDuration = duration;
targetSize = size;
}
System.out.printf("##### Page %50s %7d ms %7d bytes\n", path, duration, size);
}
}
if (targetDuration == Long.MAX_VALUE) {
fail(String.format("Failed to load page: %s", url));
}
return new PageStats(targetDuration, targetSize);
}
use of com.github.kevinsawicki.http.HttpRequest in project restfuse by eclipsesource.
the class Response_Test method setUp.
@Before
public void setUp() throws MalformedURLException {
HttpRequest httpRequest = mockRequest();
response = new ResponseImpl(httpRequest);
}
Aggregations