org.apache.http.client.fluent.Form Java Examples

The following examples show how to use org.apache.http.client.fluent.Form. 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: AweSomeApi.java    From javabase with Apache License 2.0 6 votes vote down vote up
private void post() throws IOException {
    //以Http/1.1版本协议执行一个POST请求,同时配置Expect-continue handshake达到性能调优,
    //请求中包含String类型的请求体并将响应内容作为byte[]返回
    Request.Post("http://blog.csdn.net/vector_yi")
            .useExpectContinue()
            .version(HttpVersion.HTTP_1_1)
            .bodyString("Important stuff", ContentType.DEFAULT_TEXT)
            .execute().returnContent().asBytes();


    //通过代理执行一个POST请求并添加一个自定义的头部属性,请求包含一个HTML表单类型的请求体
    //将返回的响应内容存入文件
    Request.Post("http://blog.csdn.net/vector_yi")
            .addHeader("X-Custom-header", "stuff")
            .viaProxy(new HttpHost("myproxy", 8080))
            .bodyForm(Form.form().add("username", "vip").add("password", "secret").build())
            .execute().saveContent(new File("result.dump"));

    Request.Post("http://targethost/login")
            .bodyForm(Form.form().add("username",  "vip").add("password",  "secret").build())
            .execute().returnContent();


}
 
Example #2
Source File: PushbulletNotifier.java    From yfiton with Apache License 2.0 6 votes vote down vote up
@Override
protected AccessTokenData requestAccessTokenData(AuthorizationData authorizationData) throws NotificationException {
    try {
        String authorizationCode = authorizationData.getAuthorizationCode();

        String response =
                Request.Post(getAccessTokenUrl(authorizationCode).get()).bodyForm(
                        Form.form()
                                .add("client_id", getClientId())
                                .add("client_secret", getClientSecret())
                                .add("code", authorizationCode)
                                .add("grant_type", "authorization_code").build())
                        .execute().returnContent().asString();

        JsonObject json = new JsonParser().parse(response).getAsJsonObject();

        String accessToken = json.get("access_token").getAsString();
        String tokenType = json.get("token_type").getAsString();

        return new AccessTokenData(accessToken, ImmutableMap.of("tokenType", tokenType));
    } catch (IOException e) {
        throw new NotificationException(e);
    }
}
 
Example #3
Source File: PushbulletNotifier.java    From yfiton with Apache License 2.0 6 votes vote down vote up
@Override
protected AccessTokenData requestAccessTokenData(AuthorizationData authorizationData) throws NotificationException {
    try {
        String authorizationCode = authorizationData.getAuthorizationCode();

        String response =
                Request.Post(getAccessTokenUrl(authorizationCode).get()).bodyForm(
                        Form.form()
                                .add("client_id", getClientId())
                                .add("client_secret", getClientSecret())
                                .add("code", authorizationCode)
                                .add("grant_type", "authorization_code").build())
                        .execute().returnContent().asString();

        JsonObject json = new JsonParser().parse(response).getAsJsonObject();

        String accessToken = json.get("access_token").getAsString();
        String tokenType = json.get("token_type").getAsString();

        return new AccessTokenData(accessToken, ImmutableMap.of("tokenType", tokenType));
    } catch (IOException e) {
        throw new NotificationException(e);
    }
}
 
Example #4
Source File: ApiCalls.java    From demo with MIT License 5 votes vote down vote up
/**
 * Use the API to register a user
 * @param username some username
 * @param password a really good password (otherwise it will probably respond with a complaint
 * @return returns the body of the result, if you wish to use it.
 */
public static String registerUser(String username, String password) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/register")
                .bodyForm(Form.form().add("username", username).add("password", password).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #5
Source File: ApiCalls.java    From demo with MIT License 5 votes vote down vote up
public static String registerBook(String title) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/registerbook")
                .bodyForm(Form.form().add("book", title).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #6
Source File: ApiCalls.java    From demo with MIT License 5 votes vote down vote up
public static String registerBorrowers(String name) {
    try {
        final Content content = Request.Post("http://localhost:8080/demo/registerborrower")
                .bodyForm(Form.form().add("borrower", name).build())
                .execute().returnContent();
        return content.asString();
    } catch (IOException e) {
        e.printStackTrace();
        return "";
    }
}
 
Example #7
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 #8
Source File: Test.java    From javabase with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    Content dd = Request.Post("http://s.dianping.com/ajax/json/activity/offline/followNoteAdd")
            .addHeader("Cookie", "isChecked=checked; JSESSIONID=5F9986BAAD08E91A40A18F9B16207DF0; _hc.v=7ff280b3-a676-c8dc-1a84-e5c9067f4dce.1534824829; _lxsdk_cuid=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; _lxsdk=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; cityid=1; citypinyin=shanghai; cityname=5LiK5rW3; s_ViewType=10; Hm_lvt_4c4fc10949f0d691f3a2cc4ca5065397=1534137110,1534904349; m_flash2=1; dper=d0a06116fb82790b7f4b503d4d3819545532d655172fbcce35647455fd2970d565f1c804897a94a679d5f9ea51178e6a77bdd3aa929cc272531255fda8f4c9869554ee3733589bd55adf4a5b7281ab234461678ea971200d578e18f7aef57fc2; ll=7fd06e815b796be3df069dec7836c3df; ua=18638217959; Hm_lpvt_4c4fc10949f0d691f3a2cc4ca5065397=1534904979; edper=0a7c1b58f873e7f2d6b8cc9821f469e2b7bb79faed2ed581c1592876d7643944; aburl=1; cye=dplab; ta.uuid=1032881519540281362; isUuidUnion=true; iuuid=1655ab04f9ac8-00e38d0412b1cf-34677909-1fa400-1655ab04f9bc8; dpUserId=21304984; mtUserId=\"\"; pvhistory=\"6L+U5ZuePjo8L3N0YXRpY3Rlc3QvbG9nZXZlbnQ/bmFtZT1XaGVyZUFtSUZhaWwmaW5mbz1odG1sLSU1QiU3QiUyMmNvZGUlMjIlM0EzJTJDJTIybWVzc2FnZSUyMiUzQSUyMlRpbWVvdXQlMjBleHBpcmVkJTIyJTdEJTVEJmNhbGxiYWNrPVdoZXJlQW1JMTE1MzUwOTMxMjk2OTI+OjwxNTM1MDkzMTI5NzU5XV9b\"; ri=1000310100; m_set_info=%7B%22ri%22%3A%221000310100%22%2C%22rv%22%3A%221535093140885%22%2C%22ui%22%3A%226081504%22%7D; rv=1535093140885; cy=1; _lx_utm=utm_source%3Ddp_pc_event; _lxsdk_s=1656aecd48d-b4d-6d4-d8d%7C%7C96")
            .bodyForm(Form.form().add("offlineActivityId", "504460353").add("noteBody", "ddd").build())
            .execute().returnContent();
    log.info(dd.asString());
}
 
Example #9
Source File: MailWebApi.java    From sendcloud4j with MIT License 5 votes vote down vote up
private Form convertFrom(Map<String, String> parameters) {
    Form form = Form.form();
    for (Map.Entry<String, String> param : parameters.entrySet()) {
        form.add(param.getKey(), param.getValue());
    }
    form.add("apiUser", sendCloud.apiUser());
    form.add("apiKey", sendCloud.apiKey());

    return form;
}
 
Example #10
Source File: FormTest.java    From wisdom with Apache License 2.0 5 votes vote down vote up
@Test
public void testFormSubmissionAsFormURLEncoded() throws InterruptedException, IOException {
    Router router = prepareServer();

    // Prepare the router with a controller
    Controller controller = new DefaultController() {
        @SuppressWarnings("unused")
        public Result submit() {
            final Map<String, List<String>> form = context().form();
            // String
            if (!form.get("key").get(0).equals("value")) {
                return badRequest("key is not equals to value");
            }

            // Multiple values
            List<String> list = form.get("list");
            if (!(list.contains("1") && list.contains("2"))) {
                return badRequest("list does not contains 1 and 2");
            }

            return ok(context().header(HeaderNames.CONTENT_TYPE));
        }
    };
    Route route = new RouteBuilder().route(HttpMethod.POST)
            .on("/")
            .to(controller, "submit");
    when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class))).thenReturn(route);

    server.start();
    waitForStart(server);

    int port = server.httpPort();

    final HttpResponse response = Request.Post("http://localhost:" + port + "/").bodyForm(
            Form.form().add("key", "value").add("list", "1").add("list", "2").build()
    ).execute().returnResponse();

    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
    assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.FORM);
}
 
Example #11
Source File: ParallelStats.java    From uncc2014watsonsim with GNU General Public License v2.0 4 votes vote down vote up
/** Send Statistics to the server */
private void report(int[] correct) {
	
	// At worst, give an empty branch and commit
	String branch = "", commit = "";
	if (System.getenv("TRAVIS_BRANCH") != null) {
		// Use CI information if possible.
		branch = System.getenv("TRAVIS_BRANCH");
		commit = System.getenv("TRAVIS_COMMIT");
	} else {
		// Otherwise take a stab at it ourselves.
		try {
		  	Repository repo = new FileRepositoryBuilder()
		  		.readEnvironment()
		  		.findGitDir()
		  		.build();
		   	commit = repo
	   			.resolve("HEAD")
	   			.abbreviate(10)
	   			.name();
		   	if (commit == null) {
		   		commit = "";
		   		log.warn("Problem finding git repository.\n"
		   				+ "Resulting stats will be missing information.");
		   	}
			branch = repo.getBranch();
		} catch (IOException ex) {
			// Well at least we tried.
		}
	}
	// Generate report
	List<NameValuePair> response = Form.form()
			.add("run[branch]", branch)
			.add("run[commit_hash]", commit.substring(0, 10))
			.add("run[dataset]", dataset)
			.add("run[top]", String.valueOf(correct[0]))
			.add("run[top3]", String.valueOf(correct[0] + correct[1] + correct[2]))
			.add("run[available]", String.valueOf(available))
			.add("run[rank]", String.valueOf(total_inverse_rank))
			.add("run[total_questions]", String.valueOf(questionsource.size()))
			.add("run[total_answers]", String.valueOf(total_answers))
			.add("run[confidence_histogram]", StringUtils.join(new int[100], " "))
			.add("run[confidence_correct_histogram]", StringUtils.join(new int[100], " "))
			.add("run[runtime]", String.valueOf(runtime))
			.build();
	try {
		Request.Post("http://watsonsim.herokuapp.com/runs.json").bodyForm(response).execute();
	} catch (IOException e) {
		log.warn("Error uploading stats. Ignoring. "
				+ "Details follow.", e);
	}
	

	log.info(correct[0] + " of " + questionsource.size() + " correct");
	log.info(available + " of " + questionsource.size() + " could have been");
	log.info("Mean Inverse Rank " + total_inverse_rank);
}
 
Example #12
Source File: HttpClientPostingLiveTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
public void whenPostFormUsingHttpClientFluentAPI_thenCorrect() throws IOException {
    final HttpResponse response = Request.Post(SAMPLE_URL).bodyForm(Form.form().add("username", DEFAULT_USER).add("password", DEFAULT_PASS).build()).execute().returnResponse();

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}