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


Java HttpPost.addHeader方法代码示例

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


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

示例1: register

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
private void register(RegisterModel model) throws Exception {
	String url = "http://" + properties.getScouter().getHost() + ":" + properties.getScouter().getPort() + "/register";
	
       String param = new Gson().toJson(model);

       HttpPost post = new HttpPost(url);
       post.addHeader("Content-Type","application/json");
       post.setEntity(new StringEntity(param));
     
       CloseableHttpClient client = HttpClientBuilder.create().build();
     
       // send the post request
       HttpResponse response = client.execute(post);
       
       if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
       		logger.info("Register message sent to [{}] for [{}].", url, model.getObject().getDisplay());
       } else {
        	logger.warn("Register message sent failed. Verify below information.");
        	logger.warn("[URL] : " + url);
        	logger.warn("[Message] : " + param);
        	logger.warn("[Reason] : " + EntityUtils.toString(response.getEntity(), "UTF-8"));
       }
}
 
开发者ID:nices96,项目名称:scouter-pulse-aws-monitor,代码行数:24,代码来源:GetMonitoringInstances.java

示例2: execute

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Override
public T execute() throws ClientProtocolException, IOException {
    HttpPost post = new HttpPost(InstagramConstants.API_URL + getUrl());
    post.addHeader("Connection", "close");
    post.addHeader("Accept", "*/*");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    post.addHeader("Cookie2", "$Version=1");
    post.addHeader("Accept-Language", "en-US");
    post.addHeader("User-Agent", InstagramConstants.USER_AGENT);
    
    log.debug("User-Agent: " + InstagramConstants.USER_AGENT);
    String payload = getPayload();
    log.debug("Base Payload: " + payload);
    
    if (isSigned()) {
        payload = InstagramHashUtil.generateSignature(payload);
    }
    log.debug("Final Payload: " + payload);
    post.setEntity(new StringEntity(payload));
    
    HttpResponse response = api.getClient().execute(post);
    api.setLastResponse(response);
    
    int resultCode = response.getStatusLine().getStatusCode();
    String content = EntityUtils.toString(response.getEntity());
    
    post.releaseConnection();

    return parseResult(resultCode, content);
}
 
开发者ID:brunocvcunha,项目名称:instagram4j,代码行数:31,代码来源:InstagramPostRequest.java

示例3: testService

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@RequestMapping(value = "testService", method = RequestMethod.POST)
public Object testService(@RequestParam(value = "ipPort", required = true) String ipPort,
    @RequestBody GrpcServiceTestModel model) throws Exception {
  String serviceUrl = "http://" + ipPort + "/service/test";
  HttpPost request = new HttpPost(serviceUrl);
  request.addHeader("content-type", "application/json");
  request.addHeader("Accept", "application/json");
  try {
    StringEntity entity = new StringEntity(gson.toJson(model), "utf-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    request.setEntity(entity);
    HttpResponse httpResponse = httpClient.execute(request);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
      String minitorJson = EntityUtils.toString(httpResponse.getEntity());
      Object response = gson.fromJson(minitorJson, new TypeToken<Object>() {}.getType());
      return response;
    }
  } catch (Exception e) {
    throw e;
  }
  return null;
}
 
开发者ID:venus-boot,项目名称:saluki,代码行数:24,代码来源:ServiceTestController.java

示例4: send

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public void send(List<Map<Object, Object>> events, AsyncSuccessCallback<ProducedEventsResult> onSuccess, AsyncFailCallback onFail, AsyncCancelledCallback onCancel) throws IOException, InterruptedException {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();

    String url = String.format("%s/%s/bulk-produce", this.endpoint, this.topicId);
    System.out.println(url);
    HttpPost httpPost = new HttpPost(url);
    httpPost.addHeader("Authorization", this.writeApiKey);
    httpPost.addHeader("Content-type", this.format);

    String jsonString = MAPPER.writeValueAsString(events);
    HttpEntity entity = new ByteArrayEntity(jsonString.getBytes());
    httpPost.setEntity(entity);

    ResponseParser<ProducedEventsResult> parser = new BulkProduceEventsParser();
    AsyncCallback cb = new AsyncCallback(httpClient, parser, MAPPER, onSuccess, onFail, onCancel);
    httpClient.execute(httpPost, cb);
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:19,代码来源:PyroclastProducer.java

示例5: getRequest

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

    String requestURL = "http://200.152.124.172/billing/webservice/Server.php";
    
    HttpPost httpPost = new HttpPost(requestURL);
    httpPost.addHeader("SOAPAction", "\"mostra_creditos\"");
    httpPost.addHeader("Content-Type", "text/xml");

    // prepare POST body
    String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " +
            "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " +
            "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " +
            "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" +
            "><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" +
            "<chave xsi:type=\"xsd:string\">" +
            acc.data +
            "</chave><username xsi:type=\"xsd:string\">" +
            acc.username.replaceAll("^12", "") +
            "</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>";
    Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", ""));
    // set POST body
    HttpEntity entity = new StringEntity(body);
    httpPost.setEntity(entity);
    return httpPost;
}
 
开发者ID:treasure-lau,项目名称:CSipSimple,代码行数:28,代码来源:Mobex.java

示例6: 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-stock-push,代码行数:31,代码来源:HttpUtils.java

示例7: executeHttpPost

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Performs HTTP Post request with OAuth authentication for the endpoint
 * with the given path, with the given JSON as payload and the given HTTP
 * headers.
 * 
 * @param path
 *            the path to be called.
 * @param headers
 *            map with HTTP header names and values to be included in the
 *            request.
 * @param jsonContent
 *            the JSON content to be posted.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
CloseableHttpResponse executeHttpPost(String path, Map<String, String> headers, String jsonContent)
		throws ClientProtocolException, IOException {
	logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);

	HttpPost httpPost = createHttpPost(baseUri + path);

	if (headers != null) {
		for (String header : headers.keySet()) {
			httpPost.addHeader(header, headers.get(header));
		}
	}

	if (jsonContent != null) {
		StringEntity input = new StringEntity(jsonContent);
		input.setContentType(MediaType.APPLICATION_JSON);
		httpPost.setEntity(input);
	}

	CloseableHttpClient httpClient = HttpClients.createDefault();
	CloseableHttpResponse response = httpClient.execute(httpPost);

	logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_JSON_CONTENT, baseUri, path, jsonContent);
	return response;
}
 
开发者ID:SAP,项目名称:cloud-ariba-partner-flow-extension-ext,代码行数:41,代码来源:OpenApisEndpoint.java

示例8: getByIds

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Retorna a lista de boletos emitidos por códigos de pedidos
 * @param pedidos: Lista de códigos de pedidos os quais deseja retornar os boletos
 * @return String: Link contendo os boletos relacionados aos códigos de pedidos enviados
 */
public String getByIds(Set<String> pedidos) throws IOException, PJBankException {
    PJBankClient client = new PJBankClient(this.endPoint.concat("/transacoes/lotes"));
    HttpPost httpPost = client.getHttpPostClient();
    httpPost.addHeader("x-chave", this.getChave());

    JSONArray pedidosArray = new JSONArray(pedidos);

    JSONObject params = new JSONObject();
    params.put("pedido_numero", pedidosArray);

    httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));

    String response = EntityUtils.toString(client.doRequest(httpPost).getEntity());
    JSONObject responseObject = new JSONObject(response);

    return responseObject.getString("linkBoleto");
}
 
开发者ID:pjbank,项目名称:pjbank-java-sdk,代码行数:23,代码来源:BoletosManager.java

示例9: postOverrideContentType

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
@Test public void postOverrideContentType() throws Exception {
  server.enqueue(new MockResponse());

  HttpPost httpPost = new HttpPost();
  httpPost.setURI(server.url("/").url().toURI());
  httpPost.addHeader("Content-Type", "application/xml");
  httpPost.setEntity(new StringEntity("<yo/>"));
  client.execute(httpPost);

  RecordedRequest request = server.takeRequest();
  assertEquals(request.getHeader("Content-Type"), "application/xml");
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:13,代码来源:OkApacheClientTest.java

示例10: addModuleToApp

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Adds the module to the app
 *
 * @param customerName
 *        the name of the customer which owns the app
 * @param appName
 *        the name of the app
 * @param moduleName
 *        the name of the module to add
 * @return request object to check status codes and return values
 */
public Response addModuleToApp( String customerName, String appName, String moduleName )
{
	HttpPost request = new HttpPost(
		this.yambasBase + "customers/" + customerName + "/apps/" + appName + "/usedmodules" );
	setAuthorizationHeader( request );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );

	final List<NameValuePair> data = new ArrayList<NameValuePair>( );
	data.add( new BasicNameValuePair( "moduleName", moduleName ) );

	try
	{
		request.setEntity( new UrlEncodedFormEntity( data ) );
		final HttpResponse response = this.client.execute( request );

		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
开发者ID:ApinautenGmbH,项目名称:integration-test-helper,代码行数:35,代码来源:AomHttpClient.java

示例11: getTrend

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Get trend data; interval is in months. Up to five keywords may be entered. Calling this frequently will result in denied query
 * @param keywords Keywords to query. Up to five may be queried at a time
 * @param startDate Start date. Format is in "mm/yyyy"
 * @param deltaMonths Time, in months, from start date for which to retrieve data
 * @return Trend data
 */
public static Trend getTrend(String[] keywords, String startDate, int deltaMonths) {

	StringBuilder sb = new StringBuilder();
	sb.append(PUBLIC_URL);

	StringBuilder param_q = new StringBuilder();
	for(String each : keywords) {
		param_q.append(each);
		param_q.append(',');
	}
	param_q.setLength(param_q.length()-1);

	append(sb, "q", param_q.toString());
	append(sb, "cid", "TIMESERIES_GRAPH_0");
	append(sb, "export", "3");
	append(sb, "date", startDate + "+" + deltaMonths + "m");
	append(sb, "hl", "en-US");

	HttpPost post = new HttpPost(sb.toString());
	post.addHeader("Cookie", cookieString);

	String response = null;

	try(CloseableHttpResponse httpResponse = httpClient.execute(post)) {
		HttpEntity httpEntity = httpResponse.getEntity();
		response = EntityUtils.toString(httpEntity);
		EntityUtils.consume(httpEntity);
	} catch (IOException e) {
		e.printStackTrace();
	}

	return parseResponse(response, keywords);

}
 
开发者ID:Jaewan-Yun,项目名称:Cryptocurrency-Java-Wrappers,代码行数:42,代码来源:GoogleTrends.java

示例12: addAdmin

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Adiciona uma pessoa física como administradora da conta digital
 * @param email: E-mail da pessoa física à ser adicionada como administradora
 * @return boolean
 */
public boolean addAdmin(String email) throws IOException, PJBankException {
    PJBankClient client = new PJBankClient(this.endPoint.concat("/administradores"));
    HttpPost httpPost = client.getHttpPostClient();
    httpPost.addHeader("x-chave-conta", this.chave);

    JSONObject params = new JSONObject();
    params.put("email", email);

    httpPost.setEntity(new StringEntity(params.toString(), StandardCharsets.UTF_8));

    return client.doRequest(httpPost).getStatusLine().getStatusCode() == 200;
}
 
开发者ID:pjbank,项目名称:pjbank-java-sdk,代码行数:18,代码来源:ContaDigitalManager.java

示例13: httpPost

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
/**
 * Http POST 字符串
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param body
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

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

    if (StringUtils.isNotBlank(body)) {
        post.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return convert(httpClient.execute(post));
}
 
开发者ID:linkingli,项目名称:FaceDistinguish,代码行数:34,代码来源:HttpUtil.java

示例14: createHttpRequest

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
protected HttpPost createHttpRequest() {
	String url = InstagramConstants.API_URL + getUrl();
	log.info("Direct-share URL: " + url);

	HttpPost post = new HttpPost(url);
	post.addHeader("User-Agent", InstagramConstants.USER_AGENT);
	post.addHeader("Connection", "keep-alive");
	post.addHeader("Proxy-Connection", "keep-alive");
	post.addHeader("Accept", "*/*");
	post.addHeader("Content-Type", "multipart/form-data; boundary=" + api.getUuid());
	post.addHeader("Accept-Language", "en-US");
	return post;
}
 
开发者ID:brunocvcunha,项目名称:instagram4j,代码行数:14,代码来源:InstagramDirectShareRequest.java

示例15: auth

import org.apache.http.client.methods.HttpPost; //导入方法依赖的package包/类
public static void auth() {
    CloseableHttpClient httpClient = buildHttpClient();
    HttpPost httpPost = new HttpPost(UrlConfig.auth);

    httpPost.addHeader(CookieManager.cookieHeader());
    httpPost.setEntity(new StringEntity("appid=otn", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        CookieManager.touch(response);
    } catch (IOException e) {
        logger.error("auth error", e);
    }
}
 
开发者ID:justice-code,项目名称:Thrush,代码行数:14,代码来源:HttpRequest.java


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