當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。