當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpClients.createDefault方法代碼示例

本文整理匯總了Java中org.apache.http.impl.client.HttpClients.createDefault方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpClients.createDefault方法的具體用法?Java HttpClients.createDefault怎麽用?Java HttpClients.createDefault使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.http.impl.client.HttpClients的用法示例。


在下文中一共展示了HttpClients.createDefault方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: client

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
@Test
public void client() throws URISyntaxException, IOException {

    CloseableHttpClient httpclient = HttpClients.createDefault();

    URI uri = new URIBuilder()
            .setScheme("http")
            .setHost("www.google.com")
            .setPath("/search")
            .setParameter("q", "httpclient")
            .setParameter("btnG", "Google Search")
            .setParameter("aq", "f")
            .setParameter("oq", "")
            .build();
    HttpGet httpget = new HttpGet(uri);
    CloseableHttpResponse response = httpclient.execute(httpget);
}
 
開發者ID:daishicheng,項目名稱:outcomes,代碼行數:18,代碼來源:TestHttpCore.java

示例2: postMessage

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
public boolean postMessage(String url, String message) {
	boolean ret = true;
	
	try {
		CloseableHttpClient client = HttpClients.createDefault();
	    HttpPost httpPost = new HttpPost(URL + url);
	 
	    StringEntity se = new StringEntity(message);
	    
	    httpPost.setEntity(se);
	    
	    CloseableHttpResponse response = client.execute(httpPost);
	    
	    if (response.getStatusLine().getStatusCode() != 200) {
	    	ret = false;
	    }
	    
	    client.close();
	} catch (Exception e) {
		e.printStackTrace();
		ret = false;
		System.exit(-1);
	}
	
	return ret;
}
 
開發者ID:gamefest2017,項目名稱:ants,代碼行數:27,代碼來源:Client.java

示例3: connect

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
public Map<String, String> connect(String url, Map<String, Object> parameters) throws ManagerResponseException {

        Map<String, String> response = new HashMap<String, String>();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair("j_username", (String) parameters.get("login")));
        nvps.add(new BasicNameValuePair("j_password", (String) parameters.get("password")));
        localContext = HttpClientContext.create();
        localContext.setCookieStore(new BasicCookieStore());
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            CloseableHttpResponse httpResponse = httpclient.execute(httpPost, localContext);
            ResponseHandler<String> handler = new CustomResponseErrorHandler();
            String body = handler.handleResponse(httpResponse);
            response.put(BODY, body);
            httpResponse.close();
        } catch (Exception e) {
            authentificationUtils.getMap().clear();
            throw new ManagerResponseException(e.getMessage(), e);
        }

        return response;
    }
 
開發者ID:oncecloud,項目名稱:devops-cstack,代碼行數:25,代碼來源:RestUtils.java

示例4: send

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * Makes a HTTP request to the given URL using the given request body,
 * parameters and HTTP headers. The parameters are used as URL parameters,
 * but if there's a parameter "resourceId", it's added directly to the end
 * of the URL. If there's no request body, the value can be null.
 *
 * @param url URL where the request is sent
 * @param params request parameters
 * @param requestBody request body
 * @param headers HTTP headers to be added to the request
 * @return response as string
 */
@Override
public ClientResponse send(String url, String requestBody, Map<String, ?> params, Map<String, String> headers) {
    // Build target URL
    url = ClientUtil.buildTargetURL(url, params);

    // Create HTTP client
    CloseableHttpClient httpClient = HttpClients.createDefault();

    // Build request
    HttpUriRequest request = this.buildtHttpRequest(url, requestBody, headers);

    LOGGER.info("Starting HTTP {} operation.", request.getMethod());

    // Add headers
    if (headers != null && !headers.isEmpty()) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            LOGGER.debug("Add header : \"{}\" = \"{}\"", entry.getKey(), entry.getValue());
            request.setHeader(entry.getKey(), entry.getValue());
        }
    }

    try {
        //Send the request; It will immediately return the response in HttpResponse object
        CloseableHttpResponse response = httpClient.execute(request);
        // Get Content-Type header
        Header[] contentTypeHeader = response.getHeaders("Content-Type");
        String contentType = null;
        // Check for null and empty
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            contentType = contentTypeHeader[0].getValue();
        }
        // Get Status Code
        int statusCode = response.getStatusLine().getStatusCode();
        // Get reason phrase
        String reasonPhrase = response.getStatusLine().getReasonPhrase();

        // Get response payload
        String responseStr = ClientUtil.getResponseString(response.getEntity());

        response.close();
        httpClient.close();
        LOGGER.debug("REST response content type: \"{}\".", contentType);
        LOGGER.debug("REST response status code: \"{}\".", statusCode);
        LOGGER.debug("REST response reason phrase: \"{}\".", reasonPhrase);
        LOGGER.debug("REST response : \"{}\".", responseStr);
        LOGGER.info("HTTP {} operation completed.", request.getMethod());
        return new ClientResponse(responseStr, contentType, statusCode, reasonPhrase);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        LOGGER.warn("HTTP {} operation failed. An empty string is returned.", request.getMethod());
        return null;
    }
}
 
開發者ID:vrk-kpa,項目名稱:xrd4j,代碼行數:66,代碼來源:AbstractClient.java

示例5: HttpBuildCache

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
public HttpBuildCache(URI root) {
    if (!root.getPath().endsWith("/")) {
        throw new IncompleteArgumentException("HTTP cache root URI must end with '/'");
    }
    this.root = root;
    this.safeUri = safeUri(root);
    this.httpClient = HttpClients.createDefault();
}
 
開發者ID:lxxlxx888,項目名稱:Reer,代碼行數:9,代碼來源:HttpBuildCache.java

示例6: receive

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
@Override
public DataTransferObject receive() throws IOException {
    CloseableHttpClient httpClient = null;
    DataTransferObject dto = new DataTransferObject();
    CloseableHttpResponse response = null;
    LogInfoBean logInfoBean = new LogInfoBean();
    try {
        /**
         * HTTP connections are complex, stateful, thread-unsafe objects which need to be properly managed to function correctly.
         * HTTP connections can only be used by one execution thread at a time
         */
        httpClient = HttpClients.createDefault();
        logInfoBean.setUrl(config.getSendUrl());
        //根據請求設置URL
        HttpPost httpPost = buildPostParam();
        response = httpClient.execute(httpPost);
        String result = HttpUtil.handlerRespone(response, logInfoBean);
        logger.saveLog(logInfoBean);
        //解析JSON串
        dto = parseReceive(result);
        return dto;
    } catch (Exception e) {
        dto.setErrCode(1);
        dto.setMsg("發送短信失敗:" + e.getMessage());
        LogUtil.error(LOGGER, "send error:{}", e);
        logInfoBean.setReturnInfo(e.getMessage());
        logger.saveLog(logInfoBean);
        return dto;
    } finally {
        if (!Check.NuNObj(httpClient)) {
            httpClient.close();
        }
        if (!Check.NuNObj(response)) {
            response.close();
        }
    }
}
 
開發者ID:AsuraTeam,項目名稱:asura,代碼行數:38,代碼來源:AbstractHttpSmsReceiver.java

示例7: get

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
protected HttpResponse get(String url) throws ClientProtocolException, IOException, URISyntaxException {

        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin"));
        final HttpClientContext localContext = HttpClientContext.create();
        localContext.setCredentialsProvider(credentialsProvider);
        return httpClient.execute(createGet(url), localContext);
    }
 
開發者ID:sanjuthomas,項目名稱:kafka-connect-marklogic,代碼行數:10,代碼來源:AbstractTest.java

示例8: executeHttpPost

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * Performs HTTP Post request with OAuth authentication for the endpoint
 * with the given path, with the given binary bodies as payload. Uses
 * multipart/mixed content type.
 * 
 * @param path
 *            the path to be called.
 * @param binaryBodies
 *            the payload.
 * @return the CloseableHttpResponse object.
 * @throws ClientProtocolException
 * @throws IOException
 */
CloseableHttpResponse executeHttpPost(String path, List<BinaryBody> binaryBodies)
		throws ClientProtocolException, IOException {
	logger.debug(DEBUG_EXECUTING_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);

	HttpPost httpPost = createHttpPost(baseUri + path);
	httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MULTIPART_MIXED_BOUNDARY);

	MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

	for (BinaryBody binaryBody : binaryBodies) {
		multipartEntityBuilder.addBinaryBody(binaryBody.getBinaryBodyName(), binaryBody.getFileStream(),
				ContentType.create(binaryBody.getMediaType()), binaryBody.getFileName());
	}

	HttpEntity httpEntity = multipartEntityBuilder.setBoundary(OpenApisEndpoint.BOUNDARY).build();
	httpPost.setEntity(httpEntity);

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

	logger.debug(DEBUG_EXECUTED_HTTP_POST_FOR_WITH_BINARY_BODIES, baseUri, path);
	return response;
}
 
開發者ID:SAP,項目名稱:cloud-ariba-partner-flow-extension-ext,代碼行數:37,代碼來源:OpenApisEndpoint.java

示例9: createPOST

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * Implemented createPOST from Interface interfaceAPI (see for more details)
 *
 * @param tweet
 *            Twitter Tweet which should be posted
 * @throws UnsupportedEncodingException
 *             if text is not in Unicode
 */
@Override
public void createPOST(String tweet) throws UnsupportedEncodingException {
	httpclient = HttpClients.createDefault();
	httppost = new HttpPost(Configuration.alchemyEntityApiUri);

	// Request parameters and other properties.
	List<NameValuePair> params = new ArrayList<NameValuePair>(3);
	params.add(new BasicNameValuePair("text", tweet));
	params.add(new BasicNameValuePair("apikey", apiKey));
	params.add(new BasicNameValuePair("outputMode", outputMode));

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

}
 
開發者ID:CCWI,項目名稱:keywordEntityApiRankService,代碼行數:23,代碼來源:AlchemyEntityAPI.java

示例10: setup

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
@BeforeMethod
public void setup() {
    client = HttpClients.createDefault();
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:5,代碼來源:ConsumersRestApiTest.java

示例11: doRefreshChannel

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
@SuppressWarnings({"unchecked"})
private void doRefreshChannel(PodcastChannel channel, boolean downloadEpisodes) {
    InputStream in = null;

    try (CloseableHttpClient client = HttpClients.createDefault()) {
        channel.setStatus(PodcastStatus.DOWNLOADING);
        channel.setErrorMessage(null);
        podcastDao.updateChannel(channel);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(2 * 60 * 1000) // 2 minutes
                .setSocketTimeout(10 * 60 * 1000) // 10 minutes
                .build();
        HttpGet method = new HttpGet(channel.getUrl());
        method.setConfig(requestConfig);

        try (CloseableHttpResponse response = client.execute(method)) {
            in = response.getEntity().getContent();

            Document document = new SAXBuilder().build(in);
            Element channelElement = document.getRootElement().getChild("channel");

            channel.setTitle(StringUtil.removeMarkup(channelElement.getChildTextTrim("title")));
            channel.setDescription(StringUtil.removeMarkup(channelElement.getChildTextTrim("description")));
            channel.setImageUrl(getChannelImageUrl(channelElement));
            channel.setStatus(PodcastStatus.COMPLETED);
            channel.setErrorMessage(null);
            podcastDao.updateChannel(channel);

            downloadImage(channel);
            refreshEpisodes(channel, channelElement.getChildren("item"));
        }
    } catch (Exception x) {
        LOG.warn("Failed to get/parse RSS file for Podcast channel " + channel.getUrl(), x);
        channel.setStatus(PodcastStatus.ERROR);
        channel.setErrorMessage(getErrorMessage(x));
        podcastDao.updateChannel(channel);
    } finally {
        IOUtils.closeQuietly(in);
    }

    if (downloadEpisodes) {
        for (final PodcastEpisode episode : getEpisodes(channel.getId())) {
            if (episode.getStatus() == PodcastStatus.NEW && episode.getUrl() != null) {
                downloadEpisode(episode);
            }
        }
    }
}
 
開發者ID:airsonic,項目名稱:airsonic,代碼行數:49,代碼來源:PodcastService.java

示例12: createHttpClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
public static CloseableHttpClient createHttpClient() {
    return HttpClients.createDefault();
}
 
開發者ID:nmajorov,項目名稱:keycloak_training,代碼行數:4,代碼來源:ServiceClient.java

示例13: sendPostRequest

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
private String sendPostRequest(String url, byte[] buffer, String header) throws Throwable {
	// TODO: 默認值設置
	CloseableHttpClient httpclient = HttpClients.createDefault();
	try {
		URI uri = new URI(url);
		HttpPost httpost = new HttpPost(uri);
		ByteArrayEntity byteArrayEntity = new ByteArrayEntity(buffer, ContentType.create(header, "UTF-8"));
		httpost.setEntity(byteArrayEntity);
		CloseableHttpResponse response = httpclient.execute(httpost);
		try {
			int status = response.getStatusLine().getStatusCode();
			if (status != 200) {
				throw new Exception("Unexpected response status: " + status);
			}
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} finally {
			response.close();
		}
	} finally {
		httpclient.close();
	}
}
 
開發者ID:xsonorg,項目名稱:tangyuan2,代碼行數:24,代碼來源:HttpRpcClient.java

示例14: getSpaceId

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
public static String getSpaceId(String token, String spaceName, String environment, Boolean debug_mode) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String spaces_url = chooseSpacesUrl(environment);
    if(debug_mode){
        LOGGER.info("GET SPACE_GUID URL:" + spaces_url + spaceName);
    }

    try {
        HttpGet httpGet = new HttpGet(spaces_url + URLEncoder.encode(spaceName, "UTF-8").replaceAll("\\+", "%20"));

        httpGet = addProxyInformation(httpGet);

        httpGet.setHeader("Authorization", token);
        CloseableHttpResponse response = null;

        response = httpClient.execute(httpGet);
        String resStr = EntityUtils.toString(response.getEntity());

        if(debug_mode){
            LOGGER.info("RESPONSE FROM SPACES API:" + response.getStatusLine().toString());
        }
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonObject obj = element.getAsJsonObject();
            JsonArray resources = obj.getAsJsonArray("resources");

            if(resources.size() > 0) {
                JsonObject resource = resources.get(0).getAsJsonObject();
                JsonObject metadata = resource.getAsJsonObject("metadata");
                if(debug_mode){
                    LOGGER.info("SPACE_ID:" + String.valueOf(metadata.get("guid")).replaceAll("\"", ""));
                }
                return String.valueOf(metadata.get("guid")).replaceAll("\"", "");
            }
            else {
                if(debug_mode){
                    LOGGER.info("RETURNED NO SPACES.");
                }
                return null;
            }

        } else {
            if(debug_mode){
                LOGGER.info("RETURNED STATUS CODE OTHER THAN 200. RESPONSE: " + response.getStatusLine().toString());
            }
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
 
開發者ID:IBM,項目名稱:ibm-cloud-devops,代碼行數:57,代碼來源:AbstractDevOpsAction.java

示例15: sendSmsGetMethod

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * This method is used to send SMS using Get method  
 * @param mobileNumber String
 * @param smsText  String
 * @param countryCode String
 * @return boolean
 */
public boolean sendSmsGetMethod(String mobileNumber, String smsText,
    String countryCode) {
  CloseableHttpClient httpClient = null;
  try {
    httpClient = HttpClients.createDefault();
    String path = null;
    if (validateSettings(mobileNumber, smsText)) {

      mobileNumber = removePlusFromMobileNumber(mobileNumber);

      logger.debug("Msg91SmsProvider - after removePlusFromMobileNumber "
          + mobileNumber);

      logger.debug("Inside GET");
      path =
          getCompletePath(baseUrl + getUrl, sender, smsRoute, mobileNumber,
              authKey, country, URLEncoder.encode(smsText, "UTF-8"));

      logger.debug("Msg91SmsProvider -Executing request - " + path);

      HttpGet httpGet = new HttpGet(path);

      CloseableHttpResponse response = httpClient.execute(httpGet);
      StatusLine sl = response.getStatusLine();
      response.close();
      if (sl.getStatusCode() != 200) {
        logger.error("SMS code for " + mobileNumber + " could not be sent: "
            + sl.getStatusCode() + " - " + sl.getReasonPhrase());
      }
      return sl.getStatusCode() == 200;

    } else {
      logger.debug("Msg91SmsProvider - Some mandatory parameters are empty!");
      return false;
    }
  } catch (IOException e) {
    logger.error(e);
    return false;
  } finally {
    closeHttpResource(httpClient);
  }
}
 
開發者ID:project-sunbird,項目名稱:sunbird-utils,代碼行數:50,代碼來源:Msg91SmsProvider.java


注:本文中的org.apache.http.impl.client.HttpClients.createDefault方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。