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

The following examples show how to use org.apache.http.client.fluent.Request#addHeader() . 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: PriceLookup.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PriceInfo load(String id) throws Exception {
	String path = id.startsWith("name-") ? "name/" : "id/";
	Request request = Request.Get(API_URL + path +
			(id.startsWith("name-") ?
			id.substring(id.indexOf('-') + 1)
			: id.replace("name-", "")));
	request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());

	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), PriceInfo.class);
		}
	}
	return null;
}
 
Example 3
Source File: UploadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Given("^\"([^\"]*)\" is starting uploading a content$")
public void userStartUploadContent(String username) {
    AccessToken accessToken = userStepdefs.authenticate(username);

    CountDownLatch startSignal = new CountDownLatch(2);
    CountDownConsumeInputStream bodyStream = new CountDownConsumeInputStream(startSignal);
    Request request = Request.Post(uploadUri)
        .bodyStream(new BufferedInputStream(bodyStream, _1M), org.apache.http.entity.ContentType.DEFAULT_BINARY);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    async = Async.newInstance().execute(request, new FutureCallback<Content>() {
        
        @Override
        public void failed(Exception ex) {
        }
        
        @Override
        public void completed(Content result) {
        }
        
        @Override
        public void cancelled() {
            bodyStream.getStartSignal().countDown();
            if (bodyStream.getStartSignal().getCount() == 1) {
                isCanceled = true;
            }
        }
    });
}
 
Example 4
Source File: HttpClientWrapper.java    From adaptive-alerting with Apache License 2.0 5 votes vote down vote up
private Request buildRequestWithHeaders(Request request, Map<String, String> headers) {
    for (val entry : headers.entrySet()) {
        val key = entry.getKey();
        val value = entry.getValue();
        request.addHeader(key, value);
    }
    return request;
}
 
Example 5
Source File: RestMetricsDispatcher.java    From gradle-metrics-plugin with Apache License 2.0 5 votes vote down vote up
protected void addHeaders(Request req) {
    checkNotNull(req);

    for (Map.Entry<String, String> entry : extension.getHeaders().entrySet()) {
        req.addHeader(entry.getKey(),entry.getValue());
    }
}
 
Example 6
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
private static InputStream rawStreamingGet(Executor executor,
        String auth, String url) throws IOException {
    TRACE.fine("HTTP GET: " + url);
    String accepted =
            ContentType.APPLICATION_OCTET_STREAM.getMimeType()
            + ","
            + "application/x-compressed";
    Request request = Request
            .Get(url)
            .addHeader("accept",accepted)
            .useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    Response response = executor.execute(request);
    HttpResponse hResponse = response.returnResponse();
    int rcResponse = hResponse.getStatusLine().getStatusCode();
    
    if (HttpStatus.SC_OK == rcResponse) {
        return hResponse.getEntity().getContent();
    } else {
        // all other errors...
        String httpError = "HttpStatus is " + rcResponse + " for url " + url;
        throw new RESTException(rcResponse, httpError);
    }
}
 
Example 7
Source File: RestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String url)
        throws IOException {
    TRACE.fine("HTTP GET: " + url);
    Request request = Request.Get(url).useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    return requestGsonResponse(executor, request);
}
 
Example 8
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON response to an HTTP GET call
 * 
 * @param executor HTTP client executor to use for call
 * @param auth Authentication header contents, or null
 * @param inputString
 *            REST call to make
 * @return response from the inputString
 * @throws IOException
 */
static JsonObject getGsonResponse(Executor executor, String auth, String inputString)
        throws IOException {
    TRACE.fine("HTTP GET: " + inputString);
    Request request = Request.Get(inputString).useExpectContinue();
    
    if (null != auth) {
        request = request.addHeader(AUTH.WWW_AUTH_RESP, auth);
    }
    
    return requestGsonResponse(executor, request);
}
 
Example 9
Source File: UploadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@When("^\"([^\"]*)\" upload a content without content type$")
public void userUploadContentWithoutContentType(String username) throws Throwable {
    AccessToken accessToken = userStepdefs.authenticate(username);
    Request request = Request.Post(uploadUri)
            .bodyByteArray("some text".getBytes(StandardCharsets.UTF_8));
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    response = request.execute().returnResponse();
}
 
Example 10
Source File: GogsConfigHandler.java    From gogs-webhook-plugin with MIT License 5 votes vote down vote up
void removeRepo(String projectName) throws IOException {
    Executor executor = getExecutor();
    String gogsHookConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName;
    Request request = Request.Delete(gogsHookConfigUrl);

    if (this.gogsAccessToken != null) {
        request.addHeader("Authorization", "token " + this.gogsAccessToken);
    }

    int result = executor.execute(request).returnResponse().getStatusLine().getStatusCode();
    if (result != 204) {
        throw new IOException("Repository deletion call did not return the expected value (returned " +  result + ")");
    }
}
 
Example 11
Source File: GogsConfigHandler.java    From gogs-webhook-plugin with MIT License 5 votes vote down vote up
/**
 * Creates an empty repository (under the configured user).
 * It is created as a public repository, un-initialized.
 *
 * @param projectName the project name (repository) to create
 * @throws IOException Something went wrong (example: the repo already exists)
 */
void createEmptyRepo(String projectName) throws IOException {

    Executor executor = getExecutor();
    String gogsHooksConfigUrl = getGogsServer_apiUrl() + "user/repos";
    Request request = Request.Post(gogsHooksConfigUrl);

    if (this.gogsAccessToken != null) {
        request.addHeader("Authorization", "token " + this.gogsAccessToken);
    }

    int result = executor
            .execute(request
                    .bodyForm(Form.form()
                                  .add("name", projectName)
                                  .add("description", "API generated repository")
                                  .add("private", "true")
                                  .add("auto_init", "false")
                                  .build()
                    )
            )
            .returnResponse().getStatusLine().getStatusCode();


    if (result != 201) {
        throw new IOException("Repository creation call did not return the expected value (returned " + result + ")");
    }
}
 
Example 12
Source File: DownloadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@When("^\"([^\"]*)\" checks for the availability of the attachment endpoint$")
public void optionDownload(String username) throws Throwable {
    AccessToken accessToken = userStepdefs.authenticate(username);
    URI target = baseUri(mainStepdefs.jmapServer).setPath("/download/" + ONE_ATTACHMENT_EML_ATTACHMENT_BLOB_ID).build();
    Request request = Request.Options(target);
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    response = request.execute().returnResponse();
}
 
Example 13
Source File: DownloadStepdefs.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Request authenticatedDownloadRequest(URIBuilder uriBuilder, String blobId, String username) throws URISyntaxException {
    AccessToken accessToken = userStepdefs.authenticate(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    if (attachmentAccessTokens.containsKey(key)) {
        uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    }
    Request request = Request.Get(uriBuilder.build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.asString());
    }
    return request;
}
 
Example 14
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 15
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 16
Source File: StreamsRestActions.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
static ApplicationBundle uploadBundle(Instance instance, File bundle) throws IOException {
		
Request postBundle = Request.Post(instance.self() + "/applicationbundles");
postBundle.addHeader(AUTH.WWW_AUTH_RESP, instance.connection().getAuthorization());
postBundle.body(new FileEntity(bundle, ContentType.create("application/x-jar")));

JsonObject response = requestGsonResponse(instance.connection().executor, postBundle);

UploadedApplicationBundle uab = Element.createFromResponse(instance.connection(), response, UploadedApplicationBundle.class);
uab.setInstance(instance);
return uab;
  }
 
Example 17
Source File: RestUtils.java    From streamsx.topology with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a JSON response to an HTTP request call
 */
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    Response response = executor.execute(request);
    return gsonFromResponse(response.returnResponse());
}
 
Example 18
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a JSON response to an HTTP request call
 */
static JsonObject requestGsonResponse(Executor executor, Request request) throws IOException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    Response response = executor.execute(request);
    return gsonFromResponse(response.returnResponse());
}
 
Example 19
Source File: StreamsRestUtils.java    From streamsx.topology with Apache License 2.0 4 votes vote down vote up
static String requestTextResponse(Executor executor, Request request) throws IOException {
    request.addHeader("accept", ContentType.TEXT_PLAIN.getMimeType());
    Response response = executor.execute(request);
    return textFromResponse(response.returnResponse());
}
 
Example 20
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<>();
	}
}