当前位置: 首页>>代码示例>>Java>>正文


Java HttpPost类代码示例

本文整理汇总了Java中org.apache.http.client.methods.HttpPost的典型用法代码示例。如果您正苦于以下问题:Java HttpPost类的具体用法?Java HttpPost怎么用?Java HttpPost使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpPost类属于org.apache.http.client.methods包,在下文中一共展示了HttpPost类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: simplePost

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
/**
 * Simple Http Post.
 *
 * @param path the path
 * @param payload the payload
 * @return the closeable http response
 * @throws URISyntaxException the URI syntax exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws MininetException the MininetException
 */
public CloseableHttpResponse simplePost(String path, String payload) 
    throws URISyntaxException, IOException, MininetException {
  URI uri = new URIBuilder()
      .setScheme("http")
      .setHost(mininetServerIP.toString())
      .setPort(mininetServerPort.getPort())
      .setPath(path)
      .build();
  CloseableHttpClient client = HttpClientBuilder.create().build();
  RequestConfig config = RequestConfig
      .custom()
      .setConnectTimeout(CONNECTION_TIMEOUT_MS)
      .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
      .setSocketTimeout(CONNECTION_TIMEOUT_MS)
      .build();
  HttpPost request = new HttpPost(uri);
  request.setConfig(config);
  request.addHeader("Content-Type", "application/json");
  request.setEntity(new StringEntity(payload));
  CloseableHttpResponse response = client.execute(request);
  if (response.getStatusLine().getStatusCode() >= 300) {
    throw new MininetException(String.format("failure - received a %d for %s.", 
        response.getStatusLine().getStatusCode(), request.getURI().toString()));
  }
  return response;
}
 
开发者ID:telstra,项目名称:open-kilda,代码行数:37,代码来源:Mininet.java

示例2: testEdit

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1");
    urlb.setParameter("marketName", "eoemarket");
    urlb.setParameter("catalog", "1");
    urlb.setParameter("subCatalog", "15");
    urlb.setParameter("subCatalogName", "系统工具1");
    urlb.setParameter("targetCatalog", "1");
    urlb.setParameter("targetSubCatalog", "14");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:20,代码来源:CatalogConvertorControllerTest.java

示例3: checkOrderInfo

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
public static String checkOrderInfo(TrainQuery query) {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.checkOrderInfo);

    httpPost.addHeader(CookieManager.cookieHeader());

    httpPost.setEntity(new StringEntity(genCheckOrderInfoParam(query), ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)));

    String result = StringUtils.EMPTY;
    try(CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
        result = EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        logger.error("checkUser error", e);
    }

    return result;
}
 
开发者ID:justice-code,项目名称:Thrush,代码行数:19,代码来源:HttpRequest.java

示例4: doPost

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
/**
 * Post String
 *
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method,
                                  Map<String, String> headers,
                                  Map<String, String> querys,
                                  String body)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPost request = new HttpPost(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
}
 
开发者ID:JiaXiaohei,项目名称:elasticjob-oray-client,代码行数:31,代码来源:HttpUtils.java

示例5: getRequest

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public HttpRequestBase getRequest(SipProfile acc)  throws IOException {

    String requestURL = "https://samurai.sipgate.net/RPC2";
    HttpPost httpPost = new HttpPost(requestURL);
    // TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it
    String userpassword = acc.username + ":" + acc.data;
    String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() );
    httpPost.addHeader("Authorization", "Basic " + encodedAuthorization);
    httpPost.addHeader("Content-Type", "text/xml");
    
    // prepare POST body
    String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>";

    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
开发者ID:treasure-lau,项目名称:CSipSimple,代码行数:23,代码来源:Sipgate.java

示例6: sendHttpPost

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
@Override
public <REQ> CloseableHttpResponse sendHttpPost(String url, REQ request) {
    CloseableHttpResponse execute = null;
    String requestJson = GsonUtils.toJson(request);

    try {
        LOGGER.log(Level.FINER, "Send POST request:" + requestJson + " to url-" + url);
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(requestJson, "UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        execute = this.httpClientFactory.getHttpClient().execute(httpPost);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "was unable to send POST request:" + requestJson
            + " (displaying first 1000 chars) from url-" + url, e);
    }

    return execute;
}
 
开发者ID:SoftGorilla,项目名称:restheart-java-client,代码行数:20,代码来源:HttpConnectionUtils.java

示例7: jButtonDetenerActionPerformed

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
private void jButtonDetenerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDetenerActionPerformed

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost("http://" + ip + ":8080/proyecto-gson/servidordetener?id=" + user.getId());

            CloseableHttpResponse response = httpclient.execute(httppost);
            System.out.println(response.getStatusLine());

            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);
            response.close();
        } catch (IOException ex) {
            Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
        }
        user = null;
        jLabel1.setForeground(Color.red);
        url.setText("");
        jlabelSQL.setText("");
        this.setTitle("App [ID:?]");
    }
 
开发者ID:AmauryOrtega,项目名称:Sem-Update,代码行数:22,代码来源:VentanaPrincipal.java

示例8: process

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {

            AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE);

            if (authState.getAuthScheme() != null || authState.hasAuthOptions()) {
                return;
            }

            // If no authState has been established and this is a PUT or POST request, add preemptive authorisation
            String requestMethod = request.getRequestLine().getMethod();
            if (alwaysSendAuth || requestMethod.equals(HttpPut.METHOD_NAME) || requestMethod.equals(HttpPost.METHOD_NAME)) {
                CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
                Credentials credentials = credentialsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
                if (credentials == null) {
                    throw new HttpException("No credentials for preemptive authentication");
                }
                authState.update(authScheme, credentials);
            }
        }
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:21,代码来源:HttpClientConfigurer.java

示例9: getRequest

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
public static void getRequest(String type) {
    HttpResponse httpResponse = null;
    try {
        if (type.equals("GET")) {
            HttpGet httpGet = new HttpGet("");
            ;
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36");
            httpResponse = client.execute(httpGet);
        } else if (type.equals("POST")) {
            HttpPost httpPost = new HttpPost();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}
 
开发者ID:catgg,项目名称:CTQS,代码行数:17,代码来源:HttpClientUtil.java

示例10: _testAuthenticationHttpClient

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
  start();
  try {
    SystemDefaultHttpClient httpClient = getHttpClient();
    doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));

    // Always do a GET before POST to trigger the SPNego negotiation
    if (doPost) {
      HttpPost post = new HttpPost(getBaseURL());
      byte [] postBytes = POST.getBytes();
      ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
      InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);

      // Important that the entity is not repeatable -- this means if
      // we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
      // the test will fail.
      Assert.assertFalse(entity.isRepeatable());
      post.setEntity(entity);
      doHttpClientRequest(httpClient, post);
    }
  } finally {
    stop();
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:25,代码来源:AuthenticatorTestCase.java

示例11: getRequest

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
private HttpRequestBase getRequest(String url){
	switch(method){
	case DELETE:
		return new HttpDelete(url);
	case GET:
		return new HttpGet(url);
	case HEAD:
		return new HttpHead(url);
	case PATCH:
		return new HttpPatch(url);
	case POST:
		return new HttpPost(url);
	case PUT:
		return new HttpPut(url);
	default:
		throw new IllegalArgumentException("Invalid or null HttpMethod: " + method);
	}
}
 
开发者ID:hotpads,项目名称:datarouter,代码行数:19,代码来源:DatarouterHttpRequest.java

示例12: c

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
private HttpUriRequest c() {
    if (this.f != null) {
        return this.f;
    }
    if (this.j == null) {
        byte[] b = this.c.b();
        CharSequence b2 = this.c.b(AsyncHttpClient.ENCODING_GZIP);
        if (b != null) {
            if (TextUtils.equals(b2, "true")) {
                this.j = b.a(b);
            } else {
                this.j = new ByteArrayEntity(b);
            }
            this.j.setContentType(this.c.c());
        }
    }
    HttpEntity httpEntity = this.j;
    if (httpEntity != null) {
        HttpUriRequest httpPost = new HttpPost(b());
        httpPost.setEntity(httpEntity);
        this.f = httpPost;
    } else {
        this.f = new HttpGet(b());
    }
    return this.f;
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:27,代码来源:q.java

示例13: createObject

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
/**
 * Creates an object of the given dataModelName and moduleName
 * the appname which is set in this object will be used
 *
 * @param moduleName
 *        the modulenname
 * @param dataModelName
 *        the name of the datamodels
 * @param otherFieldsObject
 *        the other fields to set as JSONObject (the @type field will be added automatically)
 * @return request object to check status codes and return values
 */
public Response createObject( String moduleName, String dataModelName, JSONObject otherFieldsObject )
{
	final HttpPost request = new HttpPost(
		this.yambasBase + "apps/" + this.appName + "/models/" + moduleName + "/" + dataModelName );
	setAuthorizationHeader( request );
	request.addHeader( "ContentType", "application/json" );
	request.addHeader( "x-apiomat-apikey", this.apiKey );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	request.addHeader( "x-apiomat-sdkVersion", this.sdkVersion );
	try
	{
		otherFieldsObject.put( "@type", moduleName + '$' + dataModelName );
		final HttpEntity requestEntity =
			new StringEntity( otherFieldsObject.toString( ), ContentType.APPLICATION_JSON );
		request.setEntity( requestEntity );
		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
开发者ID:ApinautenGmbH,项目名称:integration-test-helper,代码行数:37,代码来源:AomHttpClient.java

示例14: ipSend

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
/**
 * send current ip to server
 */
private String ipSend() throws Exception {
    HttpClient ip_send = new DefaultHttpClient();
    HttpPost post = new HttpPost(url + "/UploadIP");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id)));
    params.add(new BasicNameValuePair("ip", ip));
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    HttpResponse httpResponse = ip_send.execute(post);
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String result = null;
        HttpEntity httpEntity = httpResponse.getEntity();
        if (httpEntity != null) {
            result = EntityUtils.toString(httpEntity);
        }
        JSONObject jsonObject = new JSONObject(result);
        int ip_save = jsonObject.getInt("ip_save");
        if (ip_save == 1) {
            return "SUCCESS";
        } else return "FAIL";
    }
    return "401 UNAUTHORIZED";
}
 
开发者ID:Luodian,项目名称:Higher-Cloud-Computing-Project,代码行数:26,代码来源:ServerUtil.java

示例15: createPOST

import org.apache.http.client.methods.HttpPost; //导入依赖的package包/类
/**
 * Implemented createPOST from Interface interfaceAPI (see for more details)
 *
 * @param message
 *            Message, which should be posted.
 * @throws UnsupportedEncodingException
 *             if text is not in Unicode
 */
public void createPOST(String message) throws UnsupportedEncodingException {
	httpclient = HttpClients.createDefault();
	httppost = new HttpPost(Configuration.meaningcloudApiUri);

	// Request parameters and other properties.
	List<NameValuePair> params = new ArrayList<NameValuePair>(3);
	params.add(new BasicNameValuePair("txt", message));
	params.add(new BasicNameValuePair("key", apiKey));
	params.add(new BasicNameValuePair("of", outputMode));
	params.add(new BasicNameValuePair("lang", lang));
	params.add(new BasicNameValuePair("tt", topictypes));

	httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

}
 
开发者ID:CCWI,项目名称:keywordEntityApiRankService,代码行数:24,代码来源:MeaningCloudAPI.java


注:本文中的org.apache.http.client.methods.HttpPost类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。