Java 类org.apache.http.client.fluent.Form 实例源码

项目: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";

    int result = executor
            .execute(Request
                    .Post(gogsHooksConfigUrl)
                    .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 + ")");
    }
}
项目:javabase    文件:AweSomeApi.java   
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();


}
项目:yfiton    文件:PushbulletNotifier.java   
@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);
    }
}
项目:gopay-java-api    文件:HttpClientAuthClientImpl.java   
@Override
public AccessToken loginApplication(AuthHeader authHeader, String grantType, String scope) {
    Form form = Form.form();
    form.add(SCOPE, scope);
    form.add(GRANT_TYPE, grantType);
    Response respose = null;

    try {
        respose = Request.Post(apiUrl + "/oauth2/token")
                .addHeader(AUTHORIZATION, authHeader.getAuhorization())
                .addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded")
                .bodyForm(form.build())
                .bodyString("grant_type=client_credentials&scope=" + scope, ContentType.APPLICATION_JSON)
                .execute();
    } catch (IOException ex) {
        throw new WebApplicationException();
    }

    return unMarshall(respose, AccessToken.class);
}
项目:yfiton    文件:PushbulletNotifier.java   
@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);
    }
}
项目:basis-java-api    文件:BasisDownload.java   
public void authenticate(String username, String password) throws 
        IOException {  

    HttpResponse response = Request.Post("https://app.mybasis.com/login")
        .bodyForm(Form.form().add("username",  username).add("password",  password).build())
        .execute().returnResponse();        

    /* find the access token */ 
    HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator("Set-Cookie"));                
    while (it.hasNext()) {
        HeaderElement elem = it.nextElement(); 
        if (elem.getName().equals("access_token")) { 
            accessToken = elem.getValue(); 
            return; 
        }
    }

    /* we didn't find an access token, we couldnt login. */ 
    throw new IOException("Unable to login");
}
项目:OpenTools    文件:CityUtil.java   
public static String getAreas() {

        String timestamp = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");

        List<NameValuePair> nameValuePairList = Form.form().add("method", "taobao.areas.get").add("app_key", "23370620").add("timestamp", timestamp).add("format", "json").add("v", "2.0").add("sign_method","md5").build();

        try {

            String s = Request.Post("http://gw.api.taobao.com/router/rest").bodyForm(nameValuePairList).execute().returnContent().asString();
            System.out.println(s);
            return s;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
项目:FOX    文件:TagMeCall.java   
/**
 * TagMe request.
 */
public JSONObject send() {
  String response = "";
  try {
    response = Requests.postForm(ENDPOINT,
        Form.form()//
            .add("key", TAGME_KEY)//
            .add("text", sentence)//
            .add("lang", lang.getLanguage())//
            .add("epsilon", epsilon)//
            .add("min_comm", min_comm)//
            .add("min_link", min_link)//
            .add("include_categories", include_categories),
        ContentType.APPLICATION_JSON);
    return new JSONObject(response);
  } catch (final IOException e) {
    LOG.error(e.getLocalizedMessage(), e);
  }
  return new JSONObject();
}
项目:QuantBridge    文件:TradePostTest.java   
@Test
public void testBuy() throws IOException {
    Response response = Request.Post(url + "/buy/" + token).bodyForm(
            Form.form()
                    .add("security", "000002")
                    .add("name", "万科A")
                    .add("price", "10.00")
                    .add("position", "10000.00")
                    .add("amount", "100")
                    .build(), Charset.forName("utf8")
    ).execute();
    String x = response.returnContent().asString();
    System.out.println(x);
}
项目:QuantBridge    文件:TradePostTest.java   
@Test
public void testSell() throws IOException {
    String response = Request.Post(url + "/sell/" + token).bodyForm(
            Form.form()
                    .add("security", "000002")
                    .add("name", "万科A")
                    .add("price", "10.00")
                    .add("position", "10000.00")
                    .add("amount", "100")
                    .build(), Charset.forName("utf8")
    ).execute().returnContent().asString();
    System.out.println(response);
}
项目:dorset-framework    文件:ApacheHttpClient.java   
private List<NameValuePair> buildFormBody(HttpParameter[] parameters) {
    Form form = Form.form();
    for (HttpParameter param : parameters) {
        form.add(param.getName(), param.getValue());
    }
    return form.build();
}
项目:JPushover    文件:JPushover.java   
/**
 * Sends a validation request to pushover ensuring that the token and user
 * is correct, that there is at least one active device on the account.
 *
 * Requires token parameter
 * Requires user parameter
 * Optional device parameter to check specific device
 *
 * @return true if token and user are valid and at least on device is on the account, false otherwise
 */
public boolean validate() {
    Objects.requireNonNull(this.pushoverToken, "Token is required for validation");
    Objects.requireNonNull(this.pushoverUser, "User is required for validation");

    final List<NameValuePair> params = Form.form()
            .add(Constants.TOKEN.toString(), this.pushoverToken)
            .add(Constants.USER.toString(), this.pushoverUser)
            .add(Constants.DEVICE.toString(), this.pushoverDevice)
            .build();

    boolean valid = false;
    try {
        final HttpResponse httpResponse = Request.Post(Constants.VALIDATION_URL.toString())
                .bodyForm(params, Consts.UTF_8)
                .execute()
                .returnResponse();

        if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HTTP_OK) {
            final String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8);
            if (StringUtils.isNotBlank(response) && response.contains("\"status\":1")) {
                valid = true;
            }
        }
    } catch (final IOException e) {
        LOG.error("Failed to send validation requeste to pushover", e);
    }

    return valid;
}
项目:sendcloud4j    文件:MailWebApi.java   
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;
}
项目:dorset-framework    文件:ApacheHttpClient.java   
private List<NameValuePair> buildFormBody(HttpParameter[] parameters) {
    Form form = Form.form();
    for (HttpParameter param : parameters) {
        form.add(param.getName(), param.getValue());
    }
    return form.build();
}
项目:HttpToolbox    文件:FluentExample.java   
private static void testFluentPost(String url) {
    try {
        String result = Request.Post(url)
                               .cookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
                               .bodyForm(Form.form().add("a", "abc123")
                                                    .add("b", "中文abc123").build(), Consts.UTF_8)
                               // 或者传入自定义类型的body
                               // ContentType包含很多常用的content-type
                               // .bodyString("Important stuff 中文abc123", ContentType.DEFAULT_TEXT)
                               .execute().returnContent().asString();
        System.out.println(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:wisdom    文件:FormTest.java   
@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);
}
项目:KBDeX    文件:KFAttachmentDownloader.java   
public void initialize(KFLoginModel login) throws Exception {
    this.login = login;
    HttpPost req = new HttpPost("http://" + login.getHost()
            + "/authenticate");

    req.setEntity(new UrlEncodedFormEntity(Form.form()
            .add("DB", login.getDBName()).add("username", login.getUser())
            .add("password", login.getPassword()).build()));
    CloseableHttpResponse res = httpClient.execute(req);
    int status = res.getStatusLine().getStatusCode();
    System.out.println(status);
}
项目:KBDeX    文件:KF5Service.java   
public boolean login(String username, String password) throws Exception {
    HttpPost method = new HttpPost(getServiceURI("account/userLogin"));
    method.setEntity(
            new UrlEncodedFormEntity(Form.form().add("userName", username).add("password", password).build()));
    registrations = getJSON(method);
    return true;
}
项目:JPushover    文件:JPushover.java   
/**
 * Sends a message to pushover
 *
 * @return JPushoverResponse instance
 */
public final JPushoverResponse push() {
    Objects.requireNonNull(this.pushoverToken, "Token is required for a message");
    Objects.requireNonNull(this.pushoverUser, "User is required for a message");
    Objects.requireNonNull(this.pushoverMessage, "Message is required for a message");

    if (Priority.EMERGENCY.equals(this.pushoverPriority)) {
        Objects.requireNonNull(this.pushoverRetry, "Retry is required on priority emergency");
        Objects.requireNonNull(this.pushoverExpire, "Expire is required on priority emergency");
    }

    final List<NameValuePair> params = Form.form()
            .add(Constants.TOKEN.toString(), this.pushoverToken)
            .add(Constants.USER.toString(), this.pushoverUser)
            .add(Constants.MESSAGE.toString(), this.pushoverMessage)
            .add(Constants.DEVICE.toString(), this.pushoverDevice)
            .add(Constants.TITLE.toString(), this.pushoverTitle)
            .add(Constants.URL.toString(), this.pushoverUrl)
            .add(Constants.RETRY.toString(), this.pushoverRetry)
            .add(Constants.EXPIRE.toString(), this.pushoverExpire)
            .add(Constants.CALLBACK.toString(), this.pushoverCallback)
            .add(Constants.URLTITLE.toString(), this.pushoverUrlTitle)
            .add(Constants.PRIORITY.toString(), this.pushoverPriority.toString())
            .add(Constants.TIMESTAMP.toString(), this.pushoverTimestamp)
            .add(Constants.SOUND.toString(), this.pushoverSound.toString())
            .add(Constants.HTML.toString(), this.pushoverHtml ? "1" : "0")
            .build();

    JPushoverResponse jPushoverResponse = new JPushoverResponse().isSuccessful(false);
    try {
        final HttpResponse httpResponse = Request.Post(Constants.MESSAGES_URL.toString())
                .bodyForm(params, Consts.UTF_8)
                .execute()
                .returnResponse();

        if (httpResponse != null) {
            final int status = httpResponse.getStatusLine().getStatusCode();

            jPushoverResponse
                .httpStatus(status)
                .response(IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8))
                .isSuccessful((status == HTTP_OK) ? true : false);
        }
    } catch (final IOException e) {
        LOG.error("Failed to send message to pushover", e);
    }

    return jPushoverResponse;
}
项目:PDFReporter-Studio    文件:HttpUtils.java   
public static Request post(String url, Form form, ServerProfile sp) throws HttpException, IOException {
    System.out.println(url);
    return HttpUtils.setRequest(Request.Post(url).bodyForm(form.build()), sp);
}
项目:uncc2014watsonsim    文件:ParallelStats.java   
/** 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);
}