Java 类org.apache.http.client.HttpClient 实例源码
项目:freemoz
文件:HttpRequest.java
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();
}
项目:netto_rpc
文件:NginxServiceProvider.java
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);
}
}
项目:TradingRobot
文件:Trading.java
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;
}
项目:Dendroid-HTTP-RAT
文件:Dialog.java
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;
}
项目:FaceDistinguish
文件:HttpUtil.java
/**
* 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));
}
项目:url-to-google-drive
文件:GoogleOauthController.java
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));
}
项目:ts-benchmark
文件:InfluxDB.java
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);
}
}
项目:ts-benchmark
文件:InfluxDB.java
@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);
}
项目:gswagon-maven-plugin
文件:GSWagonTest.java
@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());
}
项目:Hackathon_2017
文件:MainActivity.java
@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;
}
}
项目:JavaRushTasks
文件:Solution.java
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());
}
项目:neo-java
文件:CityOfZionUtil.java
/**
* 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);
}
}
项目:AppServiceRestFul
文件:Util.java
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();
}
}
项目:AppServiceRestFul
文件:Util.java
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();
}
}
项目:agendamlgr
文件:Geolocation.java
@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;
}
}
项目:java-apache-httpclient
文件:TracingHttpClientBuilderTest.java
@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));
}
项目:android-advanced-light
文件:MainActivity.java
/**
* 设置默认请求参数,并返回HttpClient
*
* @return HttpClient
*/
private HttpClient createHttpClient() {
HttpParams mDefaultHttpParams = new BasicHttpParams();
//设置连接超时
HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000);
//设置请求超时
HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000);
HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true);
HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
//持续握手
HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true);
HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams);
return mHttpClient;
}
项目:Higher-Cloud-Computing-Project
文件:ServerUtil.java
public String update_online_time(int machine_id, int user_id, int delta) throws Exception {
HttpClient task_post = new DefaultHttpClient();
HttpPost post = new HttpPost(url + "/update_online_time");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("machine_id", String.valueOf(machine_id)));
params.add(new BasicNameValuePair("user_id", String.valueOf(user_id)));
params.add(new BasicNameValuePair("delta", String.valueOf(delta)));
post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse response = task_post.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 权限通过
return "AUTHORIZED";
}
return "401 UNAUTHORIZED";
}
项目:write_api_service
文件:ResourceUtilities.java
public static Optional<String> getResponseAsString(HttpRequestBase httpRequest, HttpClient client) {
Optional<String> result = Optional.empty();
final int waitTime = 60000;
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(waitTime).setConnectTimeout(waitTime)
.setConnectionRequestTimeout(waitTime).build();
httpRequest.setConfig(requestConfig);
result = Optional.of(client.execute(httpRequest, responseHandler));
} catch (HttpResponseException httpResponseException) {
LOG.error("getResponseAsString(): caught 'HttpResponseException' while processing request <{}> :=> <{}>", httpRequest,
httpResponseException.getMessage());
} catch (IOException ioe) {
LOG.error("getResponseAsString(): caught 'IOException' while processing request <{}> :=> <{}>", httpRequest, ioe.getMessage());
} finally {
httpRequest.releaseConnection();
}
return result;
}
项目:ss-android
文件:ProxyConfig.java
private String[] downloadConfig(String url) throws Exception {
try {
HttpClient client = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
requestGet.addHeader("X-Android-MODEL", Build.MODEL);
requestGet.addHeader("X-Android-SDK_INT", Integer.toString(Build.VERSION.SDK_INT));
requestGet.addHeader("X-Android-RELEASE", Build.VERSION.RELEASE);
requestGet.addHeader("X-App-Version", AppVersion);
requestGet.addHeader("X-App-Install-ID", AppInstallID);
requestGet.setHeader("User-Agent", System.getProperty("http.agent"));
HttpResponse response = client.execute(requestGet);
String configString = EntityUtils.toString(response.getEntity(), "UTF-8");
String[] lines = configString.split("\\n");
return lines;
} catch (Exception e) {
throw new Exception(String.format("Download config file from %s failed.", url));
}
}
项目:JInsight
文件:DefaultHttpClientInstrumentationTest.java
@Override
protected HttpClient createClient() {
HttpClient httpclient;
httpclient = HttpClients.createDefault();
/*
httpclient = HttpClients.createMinimal();
httpclient = HttpClientBuilder.create().build();
httpclient = new DefaultHttpClient();
httpclient = new DecompressingHttpClient(new DefaultHttpClient())
HttpRequestExecutor executor = new HttpRequestExecutor();
executor.preProcess(request, processor, context);
HttpResponse response = executor.execute(request, connection, context);
executor.postProcess(response, processor, context);
*/
return httpclient;
}
项目:nexus3-github-oauth-plugin
文件:GithubApiClientTest.java
@Test
public void cachedPrincipalReturnsIfNotExpired() throws Exception {
HttpClient mockClient = fullyFunctionalMockClient();
GithubApiClient clientToTest = new GithubApiClient(mockClient, config);
String login = "demo-user";
char[] token = "DUMMY".toCharArray();
clientToTest.authz(login, token);
// We make 2 calls to Github for a single auth check
Mockito.verify(mockClient, Mockito.times(2)).execute(Mockito.any(HttpGet.class));
Mockito.verifyNoMoreInteractions(mockClient);
// This invocation should hit the cache and should not use the client
clientToTest.authz(login, token);
Mockito.verifyNoMoreInteractions(mockClient);
}
项目:WeChatLuckyMoney
文件:UpdateTask.java
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else {
// Close the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
return null;
}
return responseString;
}
项目:stock-api-sdk
文件:ApiUtils.java
/**
* Initializes Http Client.
*
* @return Instance of HttpClient
*/
private static HttpClient initialize() {
PoolingHttpClientConnectionManager connManager
= new PoolingHttpClientConnectionManager();
RequestConfig config = RequestConfig.custom()
.setConnectionRequestTimeout(TIME_OUT)
.setSocketTimeout(TIME_OUT).build();
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connManager).disableRedirectHandling()
.setDefaultRequestConfig(config).build();
return httpClient;
}
项目:ibm-cos-sdk-java
文件:SdkProxyRoutePlannerIntegrationTest.java
/**
* The fakeHost doesn't match the nonProxyHosts pattern, so that requests to this fakeHost
* will pass through the proxy and return successfully.
*/
private void mockSuccessfulRequest(String nonProxyHosts, String fakeHost) throws IOException {
HttpClient client = createHttpClient(nonProxyHosts);
HttpUriRequest uriRequest = new HttpGet("http://" + fakeHost);
HttpResponse response = client.execute(uriRequest);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}
项目:shibboleth-idp-oidc-extension
文件:CheckRedirectUrisTest.java
protected HttpClientBuilder initializeMockBuilder(String result) throws Exception {
HttpClientBuilder httpBuilder = Mockito.mock(HttpClientBuilder.class);
HttpClient httpClient = Mockito.mock(HttpClient.class);
if (result == null) {
Mockito.when(httpClient.execute((HttpUriRequest)Mockito.any())).thenThrow(new IOException("mock"));
} else {
HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
HttpEntity httpEntity = Mockito.mock(HttpEntity.class);
Mockito.when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream(result.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(httpEntity);
Mockito.when(httpClient.execute((HttpUriRequest)Mockito.any())).thenReturn(httpResponse);
}
Mockito.when(httpBuilder.buildClient()).thenReturn(httpClient);
return httpBuilder;
}
项目:bayou
文件:ApiSynthesisClient.java
private List<String> synthesizeHelp(String code, int maxProgramCount, Integer sampleCount) throws IOException, SynthesisError
{
_logger.debug("entering");
if(code == null)
throw new IllegalArgumentException("code may not be null");
if(maxProgramCount < 1)
throw new IllegalArgumentException("maxProgramCount must be a natural number");
if(sampleCount != null && sampleCount < 1)
throw new IllegalArgumentException("sampleCount must be a natural number if non-null");
/*
* Create request and send to server.
*/
JSONObject requestMsg = new JSONObject();
requestMsg.put("code", code);
requestMsg.put("max program count", maxProgramCount);
if(sampleCount != null)
requestMsg.put("sample count", sampleCount);
HttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost("http://" + host + ":" + port + "/apisynthesis");
post.addHeader("Origin", "http://askbayou.com");
post.setEntity(new ByteArrayEntity(requestMsg.toString(4).getBytes()));
/*
* Read and parse the response from the server.
*/
JSONObject responseBodyObj;
{
HttpResponse response = httpclient.execute(post);
if(response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 400)
{
throw new IOException("Unexpected status code: " + response.getStatusLine().getStatusCode());
}
String responseBodyAsString;
{
byte[] responseBytes = IOUtils.toByteArray(response.getEntity().getContent());
responseBodyAsString = new String(responseBytes);
}
try
{
responseBodyObj = parseResponseMessageBodyToJson(responseBodyAsString);
}
catch (IllegalArgumentException e)
{
_logger.debug("exiting");
throw new SynthesisError(e.getMessage());
}
}
_logger.debug("exiting");
return parseResponseMessageBody(responseBodyObj);
}
项目:lams
文件:HttpComponentsClientHttpRequestFactory.java
/**
* Apply the specified socket timeout to deprecated {@link HttpClient}
* implementations. See {@link #setLegacyConnectionTimeout}.
* @param client the client to configure
* @param timeout the custom socket timeout
* @see #setLegacyConnectionTimeout
*/
@SuppressWarnings("deprecation")
private void setLegacySocketTimeout(HttpClient client, int timeout) {
if (org.apache.http.impl.client.AbstractHttpClient.class.isInstance(client)) {
client.getParams().setIntParameter(
org.apache.http.params.CoreConnectionPNames.SO_TIMEOUT, timeout);
}
}
项目:elasticjob-stock-push
文件:HttpUtils.java
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
项目:ts-benchmark
文件:InfluxDB.java
@Override
public Status selectByDeviceAndSensor(TsPoint point, Double max, Double min, 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 * FROM sensor where device_code='" + point.getDeviceCode()
+ "' and sensor_code='" + point.getSensorCode() + "' and value<" + max + " and value>" + min
+ " and time>=" + TimeUnit.MILLISECONDS.toNanos(startTime.getTime()) + " and time<=" + TimeUnit.MILLISECONDS.toNanos(endTime.getTime());
NameValuePair nameValue = new BasicNameValuePair("q", 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;
} catch (Exception e) {
e.printStackTrace();
return Status.FAILED(-1);
}finally{
closeResponse(response);
closeHttpClient(hc);
}
return Status.OK(costTime);
}
项目:framework
文件:HttpClientUtil.java
public HttpClient getHttpClient() {
if (httpClient == null) {
synchronized (this) {
if (httpClient == null) {
if (pool == null) { //初始化pool
try {
afterPropertiesSet();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setConnectionManager(pool);
httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(conntimeout).setSocketTimeout(sotimeout).build());
httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
}
}
}
// 否则保持活动5秒
return 5 * 1000;
}
});
httpClient = httpClientBuilder.build();
}
}
}
return httpClient;
}
项目:Higher-Cloud-Computing-Project
文件:ServerUtil.java
public String pwdResetVal(String email_addr, String user_id, String pwd) throws Exception {
HttpClient client = new DefaultHttpClient();
String params = "";
// 如果没有输入user_id就发送user_email,否则发送user_id
if (user_id == null || user_id.equals("")) {
params.concat("?email_addr=" + email_addr);
// params.add(new BasicNameValuePair("email_addr", email_addr));
} else {
params.concat("?user_id=" + user_id);
// params.add(new BasicNameValuePair("user_id", user_id));
}
params.concat("&pwd=" + pwd);
HttpGet get = new HttpGet(url + "/PwdResetVal" + params);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
JSONObject jsonObject = new JSONObject(result);
int email_sent = jsonObject.getInt("email_sent");
if (email_sent == 1) {
return "SUCCESS";
} else
return "FAIL";
} else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
return "401 SC_UNAUTHORIZED";
}
return "UNKNOWN ERROR";
}
项目:gswagon-maven-plugin
文件:GSWagon.java
@VisibleForTesting
TransportOptions buildTransportOptions(final HttpClient client)
{
return HttpTransportOptions
.newBuilder()
.setReadTimeout(getReadTimeout())
.setConnectTimeout(getTimeout())
.setHttpTransportFactory(getTransportFactory(client))
.build();
}
项目:gswagon-maven-plugin
文件:GSWagon.java
@VisibleForTesting
Storage buildStorage(HttpClient client)
{
return StorageOptions
.newBuilder()
.setRetrySettings(buildRetrySettings())
.setTransportOptions(buildTransportOptions(client))
.setClock(NanoClock.getDefaultClock())
.setProjectId(getProjectId())
.build()
.getService();
}
项目:fort_w
文件:Web.java
/**
* @see http://literatejava.com/networks/ignore-ssl-certificate-errors-apache-httpclient-4-4/
* @return
* @throws Exception
*/
public static synchronized HttpClient getHttpClient() throws Exception
{
HttpClientBuilder b = HttpClientBuilder.create();
// setup a Trust Strategy that allows all certificates.
//
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy()
{
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
return true;
}
}).build();
b.setSslcontext(sslContext);
// don't check Hostnames, either.
// -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken
HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
// here's the special part:
// -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
// -- and create a Registry, to register it.
//
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
//Registry<ConnectionSocketFactory> socketFactoryRegistry = ;
// now, we create connection-manager using our Registry.
// -- allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build());
b.setConnectionManager(connMgr);
// finally, build the HttpClient;
// -- done!
HttpClient client = b.build();
return client;
}
项目:gswagon-maven-plugin
文件:GSWagonTest.java
@Test
public void testGetItemNotFound() throws Exception
{
expectedException.expect(new CustomMatcher<Object>(ResourceDoesNotExistException.class.getName())
{
@Override
public boolean matches(Object item)
{
return item instanceof ResourceDoesNotExistException;
}
});
final HttpClient client = strictMock(HttpClient.class);
final Storage storage = createStrictMock(Storage.class);
final GSWagon gsWagon = new GSWagon()
{
@Override
void get(Blob blob, File file) throws IOException, TransferFailedException
{
// noop
}
};
gsWagon.swapAndCloseConnection(new ConnectionPOJO(
storage,
BLOB_ID,
client
));
expect(storage.get(EasyMock.<BlobId>anyObject())).andReturn(null).once();
replay(storage);
final File outFile = temporaryFolder.newFile();
gsWagon.get("artifact", outFile);
}
项目:CityPower-Build-Sample
文件:HttpClientConfiguration.java
@Bean
public HttpClient httpClient() {
log.debug("creating HttpClient");
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
// Get the poolMaxTotal value from our application[-?].yml or default to 10 if not explicitly set
connectionManager.setMaxTotal(environment.getProperty("poolMaxTotal", Integer.class, 10));
return HttpClientBuilder
.create()
.setConnectionManager(connectionManager)
.build();
}
项目:fpm
文件:TomtomDownloader.java
public static void main(String args[]) throws IOException {
if (args.length != 4) {
throw new IllegalArgumentException("Should have 4 arguments : tomtomFolder, tomtomVersion, tomtomLogin, tomtomPassword");
}
File outputDirectory = new File(args[0]);
outputDirectory.mkdirs();
HttpClient httpClient = HttpClientBuilder.create().setMaxConnPerRoute(10).setConnectionReuseStrategy(INSTANCE).build();
MetalinkDownloader metalinkDownloader = new MetalinkDownloader(args[2], args[3], args[1], outputDirectory.getAbsolutePath(), HttpClientBuilder.create().build());
ShapefileDownloader shapefileDownloader = new ShapefileDownloader(outputDirectory, httpClient);
new TomtomDownloader(metalinkDownloader, shapefileDownloader, null).run();
}
项目:bdf2
文件:HttpClientUtils.java
public static void testWithProxy(HttpClient httpClient) {
HttpHost proxy = new HttpHost("172.16.80.8", 8080);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("yaoman", "sinochem1");
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
((DefaultHttpClient) httpClient).setCredentialsProvider(credsProvider);
}
项目:Photato
文件:FfmpegDownloader.java
private static void downloadFfmpegTools(String ffmpegUrl, HttpClient httpClient, FileSystem fileSystem) throws IOException {
HttpGet request = new HttpGet(ffmpegUrl);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// Download the zip file
File tmpFile = fileSystem.getPath(tmpFilename).toFile();
tmpFile.delete(); // Delete the tmp file in case it already exists
try (InputStream inputStream = entity.getContent();
OutputStream outputStream = new FileOutputStream(tmpFile)) {
IOUtils.copy(inputStream, outputStream);
}
// Unzip
try (ZipInputStream zis = new ZipInputStream(new FileInputStream(tmpFile))) {
ZipEntry ze;
do {
ze = zis.getNextEntry();
} while (!ze.getName().endsWith("/ffmpeg.exe"));
File newFile = fileSystem.getPath(targetFilename).toFile();
newFile.delete(); // Delete in case it already exists
byte[] buffer = new byte[4096];
try (FileOutputStream fos = new FileOutputStream(newFile)) {
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
}
}
// Delete .zipFile
tmpFile.delete();
}
}