org.apache.http.client.fluent.Request#Post ( )源码实例Demo

下面列出了org.apache.http.client.fluent.Request#Post ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: 07kit   文件: ClanService.java
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;
    }
}
 
源代码2 项目: 07kit   文件: CompletedOfferRecorder.java
@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);
	}
}
 
源代码3 项目: gogs-webhook-plugin   文件: GogsConfigHandler.java
/**
 * 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");
}
 
@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();
    }
}
 
源代码5 项目: streamsx.topology   文件: StreamsRestActions.java
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);
}
 
源代码6 项目: 07kit   文件: ClanService.java
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;
    }
}
 
源代码7 项目: 07kit   文件: ClanService.java
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;
    }
}
 
源代码8 项目: 07kit   文件: ClanService.java
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;
    }
}
 
源代码9 项目: gogs-webhook-plugin   文件: GogsConfigHandler.java
/**
 * 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 + ")");
    }
}
 
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);
    }
}
 
源代码11 项目: streamsx.topology   文件: StreamsRestActions.java
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);
  }
}
 
源代码12 项目: streamsx.topology   文件: StreamsRestActions.java
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;
  }
 
源代码13 项目: sword-lang   文件: HttpUtils.java
/**
 * 上传文件
 * @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;
}
 
源代码14 项目: 07kit   文件: PriceLookup.java
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<>();
	}
}
 
源代码15 项目: gravitee-gateway   文件: PostContentGatewayTest.java
@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));
}
 
源代码16 项目: smockin   文件: HttpClientServiceImpl.java
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()));
    }
 
源代码17 项目: smockin   文件: HttpClientUtils.java
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());
    }