Java Code Examples for org.apache.http.client.fluent.Request#bodyString()

The following examples show how to use org.apache.http.client.fluent.Request#bodyString() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 9 votes vote down vote up
public static ClanInfo create(String loginName, String ingameName, String clanName, ClanRank.Status status, int world) {
    try {
        Request request = Request.Post(API_URL + "create");
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(new CreateUpdateClanRequest(loginName, ingameName, clanName, status, world)),
                ContentType.APPLICATION_JSON);

        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), ClanInfo.class);
            } else if (response.getStatusLine().getStatusCode() == 302) {
                NotificationsUtil.showNotification("Clan", "That clan name is taken");
            } else {
                NotificationsUtil.showNotification("Clan", "Error creating clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error creating clan", e);
        return null;
    }
}
 
Example 2
Source File: SplunkMetricsDispatcher.java    From gradle-metrics-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected void postPayload(String requestBody) {
    try {

        Request postReq = Request.Post(extension.getSplunkUri());
        postReq.bodyString(requestBody , ContentType.APPLICATION_JSON);
        addHeaders(postReq);
        StatusLine status = postReq.execute().returnResponse().getStatusLine();

        if (SC_OK != status.getStatusCode()) {
            error = String.format("%s (status code: %s)", 
                status.getReasonPhrase(), status.getStatusCode());
        }
    } catch (IOException e) {
        error = e.getMessage();
    }
}
 
Example 3
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 5 votes vote down vote up
public static ClanInfo join(String loginName, String ingameName, String clanName, long clanId, boolean useId, ClanRank.Status status, int world) {
    try {
        Request request = Request.Post(API_URL + "rank/update/" + (useId ? "id" : "name"));
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(new GetOrJoinClanRequest(
                clanId,
                loginName,
                ingameName,
                clanName,
                status,
                world
        )), ContentType.APPLICATION_JSON);
        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();

        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), ClanInfo.class);
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
                NotificationsUtil.showNotification("Clan", "You have not yet been accepted into this clan");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                NotificationsUtil.showNotification("Clan", "Unable to find clan");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
                NotificationsUtil.showNotification("Clan", "You have been banned from this clan");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_EXPECTATION_FAILED) {
                NotificationsUtil.showNotification("Clan", "You have been denied access into this clan");
            } else {
                NotificationsUtil.showNotification("Clan", "Error joining clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error joining clan", e);
        return null;
    }
}
 
Example 4
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 5 votes vote down vote up
public static ClanInfo updateRank(String loginName, String ingameName, ClanInfo clan, ClanRank.Status status, int world) {
    try {
        Request request = Request.Post(API_URL + "rank/update/id");
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(new GetOrJoinClanRequest(
                clan.getClanId(),
                loginName,
                ingameName,
                clan.getName(),
                status,
                world
        )), ContentType.APPLICATION_JSON);
        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();

        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), ClanInfo.class);
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
                NotificationsUtil.showNotification("Clan", "You have not yet been accepted into this clan");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                NotificationsUtil.showNotification("Clan", "Unable to find clan");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
                NotificationsUtil.showNotification("Clan", "You have been banned from this clan");
            } else {
                NotificationsUtil.showNotification("Clan", "Error updating clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error updating clan rank", e);
        return null;
    }
}
 
Example 5
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 5 votes vote down vote up
public static SuccessResponse updateMemberRank(UpdateRankRequest updateRankRequest) {
    try {
        Request request = Request.Post(API_URL + "rank/update");
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(updateRankRequest), ContentType.APPLICATION_JSON);
        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();

        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), SuccessResponse.class);
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
                NotificationsUtil.showNotification("Clan", "You aren't allowed to update ranks");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                NotificationsUtil.showNotification("Clan", "Unable to find clan/rank");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
                NotificationsUtil.showNotification("Clan", "Unable to find clan rank");
            } else {
                NotificationsUtil.showNotification("Clan", "Error updating clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error updating member clan rank", e);
        return null;
    }
}
 
Example 6
Source File: RestMetricsDispatcher.java    From gradle-metrics-plugin with Apache License 2.0 5 votes vote down vote up
protected void postPayload(String payload) {
    checkNotNull(payload);

    try {
        Request postReq = Request.Post(extension.getRestUri());
        postReq.bodyString(payload , ContentType.APPLICATION_JSON);
        addHeaders(postReq);
        postReq.execute();
    } catch (IOException e) {
        throw new RuntimeException("Unable to POST to " + extension.getRestUri(), e);
    }
}
 
Example 7
Source File: HttpUtil.java    From wechat-mp-sdk with Apache License 2.0 5 votes vote down vote up
public static <T extends JsonRtn> T postBodyRequest(WechatRequest request, License license, Map<String, String> paramMap, Object requestBody, Class<T> jsonRtnClazz) {
    if (request == null || license == null || jsonRtnClazz == null) {
        return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "missing post request params");
    }

    String requestUrl = request.getUrl();
    String requestName = request.getName();
    List<NameValuePair> form = buildNameValuePairs(paramMap);
    String body = requestBody != null ? JSONObject.toJSONString(requestBody) : StringUtils.EMPTY;

    URI uri = buildURI(requestUrl, buildNameValuePairs(license));
    if (uri == null) {
        return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "build request URI failed");
    }

    try {
        Request post = Request.Post(uri)
                .connectTimeout(CONNECT_TIMEOUT)
                .socketTimeout(SOCKET_TIMEOUT);
        if (paramMap != null) {
            post.bodyForm(form);
        }
        if (StringUtils.isNotEmpty(body)) {
            post.bodyString(body, ContentType.create("text/html", Consts.UTF_8));
        }

        String rtnJson = post.execute().handleResponse(HttpUtil.UTF8_CONTENT_HANDLER);

        T jsonRtn = JsonRtnUtil.parseJsonRtn(rtnJson, jsonRtnClazz);
        log.info(requestName + " result:\n url={},\n form={},\n body={},\n rtn={},\n {}", uri, form, body, rtnJson, jsonRtn);
        return jsonRtn;
    } catch (Exception e) {
        String msg = requestName + " failed:\n url=" + uri + ",\n form=" + form + ",\n body=" + body;
        log.error(msg, e);
        return JsonRtnUtil.buildFailureJsonRtn(jsonRtnClazz, "post request server failed");
    }
}
 
Example 8
Source File: PriceLookup.java    From 07kit with GNU General Public License v3.0 4 votes vote down vote up
public static Map<Integer, Integer> getPrices(Collection<Integer> ids) {
	try {
		Map<Integer, Integer> prices = new HashMap<>();
		List<Integer> idsClone = new ArrayList<>(ids);

		idsClone.forEach(id -> {
			if (id == 995) {
				prices.put(id, 1);
			} else {
				PriceInfo info = PRICE_INFO_CACHE.getIfPresent(String.valueOf(id));
				if (info != null) {
					prices.put(info.getItemId(), info.getBuyAverage());
				}
			}
		});

		idsClone.removeAll(prices.keySet());

		if (idsClone.size() == 0) {
			return prices;
		}

		Request request = Request.Post(API_URL + "ids");
		request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
		request.bodyString(GSON.toJson(idsClone), ContentType.APPLICATION_JSON);

		HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
		if (response != null) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				byte[] bytes = EntityUtils.toByteArray(response.getEntity());
				List<PriceInfo> infos = GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE);
				infos.forEach(i -> {
					PRICE_INFO_CACHE.put(String.valueOf(i.getItemId()), i);
					prices.put(i.getItemId(), i.getBuyAverage());
				});
			}
		}

		return prices;
	} catch (IOException | CacheLoader.InvalidCacheLoadException e) {
		e.printStackTrace();
		return new HashMap<>();
	}
}