Java Code Examples for org.apache.http.client.HttpClient

The following are top voted examples for showing how to use org.apache.http.client.HttpClient. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: freemoz   File: HttpRequest.java   View source code 6 votes vote down vote up
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();
}
 
Example 2
Project: netto_rpc   File: NginxServiceProvider.java   View source code 6 votes vote down vote up
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);
	}
}
 
Example 3
Project: TradingRobot   File: Trading.java   View source code 6 votes vote down vote up
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;
}
 
Example 4
Project: Dendroid-HTTP-RAT   File: Dialog.java   View source code 6 votes vote down vote up
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;
    }
 
Example 5
Project: FaceDistinguish   File: HttpUtil.java   View source code 6 votes vote down vote up
/**
 * 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));
}
 
Example 6
Project: url-to-google-drive   File: GoogleOauthController.java   View source code 6 votes vote down vote up
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));
}
 
Example 7
Project: ts-benchmark   File: InfluxDB.java   View source code 6 votes vote down vote up
@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);
}
 
Example 8
Project: gswagon-maven-plugin   File: GSWagonTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 9
Project: Hackathon_2017   File: MainActivity.java   View source code 6 votes vote down vote up
@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;
    }
}
 
Example 10
Project: JavaRushTasks   File: Solution.java   View source code 6 votes vote down vote up
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());
}
 
Example 11
Project: neo-java   File: CityOfZionUtil.java   View source code 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 12
Project: AppServiceRestFul   File: Util.java   View source code 6 votes vote down vote up
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(); 
   } 
}
 
Example 13
Project: AppServiceRestFul   File: Util.java   View source code 6 votes vote down vote up
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(); 
   } 
}
 
Example 14
Project: agendamlgr   File: Geolocation.java   View source code 6 votes vote down vote up
@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;
    }
}
 
Example 15
Project: java-apache-httpclient   File: TracingHttpClientBuilderTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 16
Project: android-advanced-light   File: MainActivity.java   View source code 6 votes vote down vote up
/**
 * 设置默认请求参数,并返回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;

}
 
Example 17
Project: Higher-Cloud-Computing-Project   File: ServerUtil.java   View source code 6 votes vote down vote up
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";
    }
 
Example 18
Project: write_api_service   File: ResourceUtilities.java   View source code 6 votes vote down vote up
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;
}
 
Example 19
Project: ss-android   File: ProxyConfig.java   View source code 6 votes vote down vote up
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));
    }
}
 
Example 20
Project: JInsight   File: DefaultHttpClientInstrumentationTest.java   View source code 6 votes vote down vote up
@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;
}
 
Example 21
Project: nexus3-github-oauth-plugin   File: GithubApiClientTest.java   View source code 6 votes vote down vote up
@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);
}
 
Example 22
Project: WeChatLuckyMoney   File: UpdateTask.java   View source code 6 votes vote down vote up
@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;
}
 
Example 23
Project: stock-api-sdk   File: ApiUtils.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 24
Project: ibm-cos-sdk-java   File: SdkProxyRoutePlannerIntegrationTest.java   View source code 5 votes vote down vote up
/**
 * 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());
}
 
Example 25
Project: shibboleth-idp-oidc-extension   File: CheckRedirectUrisTest.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: bayou   File: ApiSynthesisClient.java   View source code 5 votes vote down vote up
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);
}
 
Example 27
Project: lams   File: HttpComponentsClientHttpRequestFactory.java   View source code 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 28
Project: elasticjob-stock-push   File: HttpUtils.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 29
Project: ts-benchmark   File: InfluxDB.java   View source code 5 votes vote down vote up
@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);
}
 
Example 30
Project: framework   File: HttpClientUtil.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: ts-benchmark   File: InfluxDB.java   View source code 5 votes vote down vote up
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);
		}
	}
 
Example 32
Project: Higher-Cloud-Computing-Project   File: ServerUtil.java   View source code 5 votes vote down vote up
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";
    }
 
Example 33
Project: gswagon-maven-plugin   File: GSWagon.java   View source code 5 votes vote down vote up
@VisibleForTesting
TransportOptions buildTransportOptions(final HttpClient client)
{
  return HttpTransportOptions
      .newBuilder()
      .setReadTimeout(getReadTimeout())
      .setConnectTimeout(getTimeout())
      .setHttpTransportFactory(getTransportFactory(client))
      .build();
}
 
Example 34
Project: gswagon-maven-plugin   File: GSWagon.java   View source code 5 votes vote down vote up
@VisibleForTesting
Storage buildStorage(HttpClient client)
{
  return StorageOptions
      .newBuilder()
      .setRetrySettings(buildRetrySettings())
      .setTransportOptions(buildTransportOptions(client))
      .setClock(NanoClock.getDefaultClock())
      .setProjectId(getProjectId())
      .build()
      .getService();
}
 
Example 35
Project: fort_w   File: Web.java   View source code 5 votes vote down vote up
/**
 * @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;
}
 
Example 36
Project: gswagon-maven-plugin   File: GSWagonTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 37
Project: CityPower-Build-Sample   File: HttpClientConfiguration.java   View source code 5 votes vote down vote up
@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();
}
 
Example 38
Project: fpm   File: TomtomDownloader.java   View source code 5 votes vote down vote up
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();
}
 
Example 39
Project: bdf2   File: HttpClientUtils.java   View source code 5 votes vote down vote up
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);
}
 
Example 40
Project: Photato   File: FfmpegDownloader.java   View source code 5 votes vote down vote up
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();
    }
}