Java Code Examples for org.apache.http.client.fluent.Request#Post

The following examples show how to use org.apache.http.client.fluent.Request#Post . 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: StreamsRestActions.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
static Result<Job, JsonObject> submitJob(ApplicationBundle bundle, JsonObject jco) throws IOException {
	UploadedApplicationBundle uab = (UploadedApplicationBundle) bundle;
	
	JsonObject body = new JsonObject();
	body.addProperty("application", uab.getBundleId());
	body.addProperty("preview", false);		
	body.add("jobConfigurationOverlay", jco);
	
	final AbstractStreamsConnection conn = bundle.instance().connection();
	
	Request postBundle = Request.Post(bundle.instance().self() + "/jobs");
	postBundle.addHeader(AUTH.WWW_AUTH_RESP, conn.getAuthorization());
	postBundle.body(new StringEntity(body.toString(), ContentType.APPLICATION_JSON));		
	
	JsonObject response = requestGsonResponse(conn.executor, postBundle);
	
	Job job = Job.create(bundle.instance(), response.toString());
	
	if (!response.has(SubmissionResultsKeys.JOB_ID))
		response.addProperty(SubmissionResultsKeys.JOB_ID, job.getId());

	return new ResultImpl<Job, JsonObject>(true, job.getId(),
			() -> job, response);
}
 
Example 3
Source File: CompletedOfferRecorder.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void onOfferUpdate(GrandExchangeOfferUpdatedEvent evt) {
	if (lastLoginTime == -1 || (System.currentTimeMillis() - lastLoginTime) < MIN_TIME_SINCE_LOGIN) {
		return;
	}

	//TODO be better at life 2k19
	if (evt.getOffer() != null && evt.getOffer().getTransferred() == evt.getOffer().getQuantity()) {
		String path = "";
		if (evt.getOffer().getState() == BUY_COMPLETE_STATE) {
			path += "buy/";
		} else if (evt.getOffer().getState() == SELL_COMPLETE_STATE) {
			path += "sell/";
		} else {
			return;
		}
		path += "insert/" + evt.getOffer().getItemId() + "/" + evt.getOffer().getTotalSpent() + "/" + evt.getOffer().getQuantity();

		Request request = Request.Post(API_URL + path);
		request.addHeader(SECRET_HEADER_KEY, SECRET);

		requestQueue.add(request);
	}
}
 
Example 4
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 5
Source File: GogsConfigHandler.java    From gogs-webhook-plugin with MIT License 6 votes vote down vote up
/**
 * Creates a web hook in Gogs with the passed json configuration string
 *
 * @param jsonCommand A json buffer with the creation command of the web hook
 * @param projectName the project (owned by the user) where the webHook should be created
 * @throws IOException something went wrong
 */
int createWebHook(String jsonCommand, String projectName) throws IOException {

    String gogsHooksConfigUrl = getGogsServer_apiUrl()
            + "repos/" + this.gogsServer_user
            + "/" + projectName + "/hooks";

    Executor executor = getExecutor();
    Request request = Request.Post(gogsHooksConfigUrl);

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

    String result = executor
            .execute(request.bodyString(jsonCommand, ContentType.APPLICATION_JSON))
            .returnContent().asString();
    JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result );
    return jsonObject.getInt("id");
}
 
Example 6
Source File: HttpUtils.java    From sword-lang with Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 * @param url    URL
 * @param name   文件的post参数名称
 * @param file   上传的文件
 * @return
 */
public static String postFile(String url,String name,File file){
	try {
		HttpEntity reqEntity = MultipartEntityBuilder.create().addBinaryBody(name, file).build();
		Request request = Request.Post(url);
		request.body(reqEntity);
		HttpEntity resEntity = request.execute().returnResponse().getEntity();
		return resEntity != null ? EntityUtils.toString(resEntity) : null;
	} catch (Exception e) {
		logger.error("postFile请求异常," + e.getMessage() + "\n post url:" + url);
		e.printStackTrace();
	}
	return null;
}
 
Example 7
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 8
Source File: StreamsRestActions.java    From streamsx.topology with Apache License 2.0 5 votes vote down vote up
static Toolkit uploadToolkit(StreamsBuildService connection, File path) throws IOException {
  // Make sure it is a directory
  if (! path.isDirectory()) {
    throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a directory.");
  }

  // Make sure it contains toolkit.xml
  File toolkit = new File(path, "toolkit.xml");
  if (! toolkit.isFile()) {
    throw new IllegalArgumentException("The specified toolkit path '" + path.toString() + "' is not a toolkit.");
  }

  String toolkitsURL = connection.getToolkitsURL();
  Request post = Request.Post(toolkitsURL);
  post.addHeader(AUTH.WWW_AUTH_RESP, connection.getAuthorization());
  post.bodyStream(DirectoryZipInputStream.fromPath(path.toPath()), ContentType.create("application/zip"));

  Response response = connection.getExecutor().execute(post);
  HttpResponse httpResponse = response.returnResponse();
  int statusCode = httpResponse.getStatusLine().getStatusCode();
  // TODO The API is supposed to return CREATED, but there is a bug and it
  // returns OK.  When the bug is fixed, change this to accept only OK
  if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
    String message = EntityUtils.toString(httpResponse.getEntity());
    throw RESTException.create(statusCode, message);
  }
  
  HttpEntity entity = httpResponse.getEntity();
  try (Reader r = new InputStreamReader(entity.getContent())) {
    JsonObject jresponse = new Gson().fromJson(r, JsonObject.class);
    EntityUtils.consume(entity);
    List<Toolkit> toolkitList = Toolkit.createToolkitList(connection, jresponse);

    // We expect a list of zero or one element.
    if (toolkitList.size() == 0) {
      return null;
    }
    return toolkitList.get(0);
  }
}
 
Example 9
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 10
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 11
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 12
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 13
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 14
Source File: PostContentGatewayTest.java    From gravitee-gateway with Apache License 2.0 4 votes vote down vote up
@Test
public void no_content_with_chunked_encoding_transfer() throws Exception {
    stubFor(post(urlEqualTo("/team/my_team")).willReturn(ok()));

    Request request = Request.Post("http://localhost:8082/test/my_team");

    HttpResponse response = request.execute().returnResponse();

    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());

    // Set chunk mode in request but returns raw because of the size of the content
    assertEquals(null, response.getFirstHeader("X-Forwarded-Transfer-Encoding"));

    String responseContent = StringUtils.copy(response.getEntity().getContent());
    assertEquals(0, responseContent.length());

    verify(postRequestedFor(urlEqualTo("/team/my_team"))
            .withoutHeader(HttpHeaders.TRANSFER_ENCODING));
}
 
Example 15
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<>();
	}
}
 
Example 16
Source File: HttpClientUtils.java    From smockin with Apache License 2.0 3 votes vote down vote up
public static HttpClientResponseDTO post(final HttpClientCallDTO reqDto) throws IOException {

        final Request request = Request.Post(reqDto.getUrl());

        handleRequestData(request, reqDto.getHeaders(), reqDto);

        return executeRequest(request, reqDto.getHeaders());
    }
 
Example 17
Source File: HttpClientServiceImpl.java    From smockin with Apache License 2.0 3 votes vote down vote up
HttpClientResponseDTO post(final HttpClientCallDTO reqDto) throws IOException {

        final Request request = Request.Post(reqDto.getUrl());

        HttpClientUtils.handleRequestData(request, reqDto.getHeaders(), reqDto);

        return executeRequest(request, reqDto.getHeaders(), isHttps(reqDto.getUrl()));
    }