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


Java HttpClient类代码示例

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


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

示例1: executePost

import org.apache.http.client.HttpClient; //导入依赖的package包/类
public String executePost(List<NameValuePair> urlParameters) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(this.url);

    post.setHeader("User-Agent", USER_AGENT);
    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line;
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    return result.toString();
}
 
开发者ID:boyter,项目名称:freemoz,代码行数:21,代码来源:HttpRequest.java

示例2: getServerGroups

import org.apache.http.client.HttpClient; //导入依赖的package包/类
private List<ServerAddressGroup> getServerGroups() {
	RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Constants.DEFAULT_TIMEOUT)
			.setConnectionRequestTimeout(Constants.DEFAULT_TIMEOUT).setSocketTimeout(Constants.DEFAULT_TIMEOUT)
			.build();
	HttpClient httpClient = this.httpPool.getResource();
	try {
		StringBuilder sb = new StringBuilder(50);
		sb.append(this.getServerDesc().getRegistry())
				.append(this.getServerDesc().getRegistry().endsWith("/") ? "" : "/")
				.append(this.getServerDesc().getServerApp()).append("/servers");
		HttpGet get = new HttpGet(sb.toString());
		get.setConfig(requestConfig);
		// 创建参数队列
		HttpResponse response = httpClient.execute(get);
		HttpEntity entity = response.getEntity();
		String body = EntityUtils.toString(entity, "UTF-8");
		ObjectMapper mapper = JsonMapperUtil.getJsonMapper();
		return mapper.readValue(body, mapper.getTypeFactory().constructParametricType(List.class,
				mapper.getTypeFactory().constructType(ServerAddressGroup.class)));
	} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new RuntimeException(e);
	} finally {
		this.httpPool.release(httpClient);
	}
}
 
开发者ID:sylinklee,项目名称:netto_rpc,代码行数:27,代码来源:NginxServiceProvider.java

示例3: getUsdGbp

import org.apache.http.client.HttpClient; //导入依赖的package包/类
public double getUsdGbp() {
	HttpClientBuilder hcb = HttpClientBuilder.create();
	HttpClient client = hcb.build();
	HttpGet request = new HttpGet(RequestURI.baseURL+"/v1/prices?instruments=GBP_USD");
	request.addHeader(RequestURI.headerTitle,RequestURI.accessToken);
	try {
		HttpResponse response = client.execute(request);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject resultJson = new JSONObject(result.toString());
		JSONArray priceDetails = resultJson.getJSONArray("prices");
		resultJson = priceDetails.getJSONObject(0);
		double midPrice = (resultJson.getDouble("ask") + resultJson.getDouble("bid"))/2;
		
		return 1/midPrice;
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return 0;
}
 
开发者ID:toni8810,项目名称:TradingRobot,代码行数:26,代码来源:Trading.java

示例4: getInputStreamFromUrl

import org.apache.http.client.HttpClient; //导入依赖的package包/类
public InputStream getInputStreamFromUrl(String urlBase, String urlData) throws UnsupportedEncodingException {
    	
//    	Log.d("com.connect", urlBase);
    	Log.d("com.connect", urlData);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
        String currentDateandTime = "[" + sdf.format(new Date()) + "] - ";
        currentDateandTime = URLEncoder.encode (currentDateandTime, "UTF-8");

    	urlData = URLEncoder.encode (urlData, "UTF-8");

    	if(isNetworkAvailable())
    	{
    	  InputStream content = null;
    	  try 
    	  {
    	    HttpClient httpclient = new DefaultHttpClient();
    	    HttpResponse response = httpclient.execute(new HttpGet(urlBase + currentDateandTime+ urlData));
    	    content = response.getEntity().getContent();
    	    httpclient.getConnectionManager().shutdown();
    	  } catch (Exception e) {
    	  }
    	    return content;
    	}
		return null;
    }
 
开发者ID:mwsrc,项目名称:Dendroid-HTTP-RAT,代码行数:27,代码来源:Dialog.java

示例5: httpPut

import org.apache.http.client.HttpClient; //导入依赖的package包/类
/**
 * HTTP PUT 字符串
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param body
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPut(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.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

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

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

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

    }

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

示例6: getAccessToken

import org.apache.http.client.HttpClient; //导入依赖的package包/类
private Token getAccessToken(@NotNull String code) throws IOException {
	// Initialize client
	HttpClient httpClient = HttpClientBuilder.create().build();
	HttpPost httpPost = new HttpPost(TOKEN_URL);

	// add request parameters
	List<NameValuePair> parameters = new ArrayList<>();
	parameters.add(new BasicNameValuePair("code", code));
	parameters.add(new BasicNameValuePair("client_id", CLIENT_ID));
	parameters.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
	parameters.add(new BasicNameValuePair("redirect_uri", REDIRECT_URI));
	parameters.add(new BasicNameValuePair("grant_type", GRANT_TYPE));
	httpPost.setEntity(new UrlEncodedFormEntity(parameters));

	// send request
	org.apache.http.HttpResponse response = httpClient.execute(httpPost);
	int statusCode = response.getStatusLine().getStatusCode();
	InputStream inputStream = response.getEntity().getContent();

	if (HttpUtilities.success(statusCode))
		return gson.fromJson(new InputStreamReader(inputStream), Token.class);

	throw new ApiException(HttpStatus.valueOf(statusCode));
}
 
开发者ID:dhaval-mehta,项目名称:url-to-google-drive,代码行数:25,代码来源:GoogleOauthController.java

示例7: createTestDB

import org.apache.http.client.HttpClient; //导入依赖的package包/类
private void createTestDB() {
		HttpClient hc = getHttpClient();
		HttpPost post = new HttpPost(QUERY_URL);
		HttpResponse response = null;
		try {
			List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
			String createSql = "CREATE DATABASE " + DB_NAME;
			NameValuePair nameValue = new BasicNameValuePair("q", createSql);
			nameValues.add(nameValue);
			HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8");
			post.setEntity(entity);
			response = hc.execute(post);
			closeHttpClient(hc);
//			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			closeResponse(response);
			closeHttpClient(hc);
		}
	}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:22,代码来源:InfluxDB.java

示例8: selectAvgByDeviceAndSensor

import org.apache.http.client.HttpClient; //导入依赖的package包/类
@Override
public Status selectAvgByDeviceAndSensor(String deviceCode, String sensorCode, Date startTime, Date endTime) {
	HttpClient hc = getHttpClient();
	HttpPost post = new HttpPost(QUERY_URL);
	HttpResponse response = null;
	long costTime = 0L;
	try {
		List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
		String selectSql = "SELECT MEAN(value) FROM sensor where device_code='" + deviceCode + "' and sensor_code='"
				+ sensorCode + "' and time>=" + TimeUnit.MILLISECONDS.toNanos(startTime.getTime()) + " and time<=" + TimeUnit.MILLISECONDS.toNanos(endTime.getTime());
		NameValuePair nameValue = new BasicNameValuePair("q", selectSql);
		//System.out.println(selectSql);
		nameValues.add(nameValue);
		HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8");
		post.setEntity(entity);
		long startTime1 = System.nanoTime();
		response = hc.execute(post);
		long endTime1 = System.nanoTime();
		costTime = endTime1 - startTime1;
		//System.out.println(response);
	} catch (Exception e) {
		e.printStackTrace();
		return Status.FAILED(-1);
	}finally{
		closeResponse(response);
		closeHttpClient(hc);
	}
	//System.out.println("此次查询消耗时间[" + costTime / 1000 + "]s");
	return Status.OK(costTime);
}
 
开发者ID:dbiir,项目名称:ts-benchmark,代码行数:31,代码来源:InfluxDB.java

示例9: testSwapAndCloseConnection

import org.apache.http.client.HttpClient; //导入依赖的package包/类
@Test
public void testSwapAndCloseConnection()
{
  final GSWagon gsWagon = new GSWagon()
  {
    @Override
    HttpClient buildClient()
    {
      return connectionPOJO.client;
    }
  };
  gsWagon.swapAndCloseConnection(connectionPOJO);
  assertEquals(connectionPOJO.client, gsWagon.buildClient());
  assertEquals(connectionPOJO.baseId, gsWagon.getBaseId());
  assertEquals(connectionPOJO.storage, gsWagon.getStorage());
}
 
开发者ID:drcrallen,项目名称:gswagon-maven-plugin,代码行数:17,代码来源:GSWagonTest.java

示例10: doInBackground

import org.apache.http.client.HttpClient; //导入依赖的package包/类
@Override
protected List<Pregunta> doInBackground(Void... voids) {
    try{
        HttpGet get = new HttpGet("http://192.168.43.167/goc/getQuestions.php");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        String respuesta = EntityUtils.toString(entity);
        String preguntas[] = respuesta.split("\\r\\n|\\n|\\r");
        List<Pregunta> preguntasLista = new ArrayList<>();
        for (String p:preguntas)
            preguntasLista.add(new Pregunta(p.split(";")));
        return preguntasLista;
    }catch (Exception e){
        e.printStackTrace();
        return null;
    }
}
 
开发者ID:CoEValencia,项目名称:Hackathon_2017,代码行数:19,代码来源:MainActivity.java

示例11: sendPost

import org.apache.http.client.HttpClient; //导入依赖的package包/类
public void sendPost(String url, String urlParameters) throws Exception {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost(url);
    request.addHeader("User-Agent", "Mozilla/5.0");

    List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
    String[] s = urlParameters.split("&");
    for (int i = 0; i < s.length; i++) {
        String g = s[i];
        valuePairs.add(new BasicNameValuePair(g.substring(0,g.indexOf("=")), g.substring(g.indexOf("=")+1)));
    }

    request.setEntity(new UrlEncodedFormEntity(valuePairs));
    HttpResponse response = client.execute(request);
    System.out.println("Response Code: " + response.getStatusLine().getStatusCode());

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String responseLine;
    while ((responseLine = bufferedReader.readLine()) != null) {
        result.append(responseLine);
    }

    System.out.println("Response: " + result.toString());
}
 
开发者ID:avedensky,项目名称:JavaRushTasks,代码行数:26,代码来源:Solution.java

示例12: getTestNetApiJsonAtUrl

import org.apache.http.client.HttpClient; //导入依赖的package包/类
/**
 * return the testnet URL with the given suffix.
 *
 * @param urlSuffix
 *            the url suffix to use.
 * @return the testnet URL with the given suffix.
 */
private static JSONObject getTestNetApiJsonAtUrl(final String urlSuffix) {
	try {
		final HttpGet get = new HttpGet(TESTNET_API + urlSuffix);
		final HttpClient client = getHttpClient();
		final HttpResponse response = client.execute(get);
		LOG.debug("test net status:{}", response.getStatusLine());
		final HttpEntity entity = response.getEntity();
		final String entityStr = EntityUtils.toString(entity);
		LOG.debug("test net entityStr:{}", entityStr);
		final JSONObject json = new JSONObject(entityStr);
		return json;
	} catch (final IOException e) {
		throw new RuntimeException(e);
	}
}
 
开发者ID:coranos,项目名称:neo-java,代码行数:23,代码来源:CityOfZionUtil.java

示例13: getNewHttpClient

import org.apache.http.client.HttpClient; //导入依赖的package包/类
private static HttpClient getNewHttpClient() { 
   try { 
       KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
       trustStore.load(null, null); 

       SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); 
       sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

       HttpParams params = new BasicHttpParams(); 
       HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
       HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

       SchemeRegistry registry = new SchemeRegistry(); 
       registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
       registry.register(new Scheme("https", sf, 443)); 

       ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 

       return new DefaultHttpClient(ccm, params); 
   } catch (Exception e) { 
       return new DefaultHttpClient(); 
   } 
}
 
开发者ID:wanliyang1990,项目名称:AppServiceRestFul,代码行数:24,代码来源:Util.java

示例14: encontrarCoordenadas

import org.apache.http.client.HttpClient; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public static String encontrarCoordenadas(String direccion) throws IOException{
    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = new HttpGet("https://maps.googleapis.com/maps/api/geocode/json?address="+URLEncoder.encode(direccion, StandardCharsets.UTF_8.name())+"&key="+ TokensUtils.googleApiKey);
    HttpResponse res = httpClient.execute(request);
    Map<String, Object> resultadoJSON = (Map<String, Object>) new Gson().fromJson(
        new InputStreamReader(res.getEntity().getContent()),
        Map.class
    );
    
    List<Map<String, Object>> results = (List<Map<String, Object>>) resultadoJSON.get("results");
    if(!results.isEmpty()) {
        Map<String,Object> geometry = (Map<String,Object>) results.get(0).get("geometry");
        Map<String,Object> location = (Map<String,Object>) geometry.get("location");
        Double lat = (Double) location.get("lat");
        Double lng = (Double) location.get("lng");
        //texto.results[0].geometry.location.lat
        return lat+","+lng;
    }else{
        return null;
    }
}
 
开发者ID:melchor629,项目名称:agendamlgr,代码行数:23,代码来源:Geolocation.java

示例15: testPropagationAfterRedirect

import org.apache.http.client.HttpClient; //导入依赖的package包/类
@Test
public void testPropagationAfterRedirect() throws IOException {
    {
        HttpClient client = clientBuilder.build();
        client.execute(new HttpGet(serverUrl(RedirectHandler.MAPPING)));
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(3, mockSpans.size());

    // the last one is for redirect
    MockSpan mockSpan = mockSpans.get(1);
    Assert.assertEquals(PropagationHandler.lastRequest.getFirstHeader("traceId").getValue(),
            String.valueOf(mockSpan.context().traceId()));
    Assert.assertEquals(PropagationHandler.lastRequest.getFirstHeader("spanId").getValue(),
            String.valueOf(mockSpan.context().spanId()));

    assertLocalSpan(mockSpans.get(2));
}
 
开发者ID:opentracing-contrib,项目名称:java-apache-httpclient,代码行数:20,代码来源:TracingHttpClientBuilderTest.java


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