org.apache.http.impl.client.DefaultHttpClient Java Examples

The following examples show how to use org.apache.http.impl.client.DefaultHttpClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WBFailover.java    From java-client-api with Apache License 2.0 7 votes vote down vote up
private boolean isRunning(String host) {
	try {

		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(new AuthScope(host, 7997),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpGet get = new HttpGet("http://" + host + ":7997?format=json");
		HttpResponse response = client.execute(get);
		ResponseHandler<String> handler = new BasicResponseHandler();
		String body = handler.handleResponse(response);
		if (body.contains("Healthy")) {
			return true;
		}

	} catch (Exception e) {
		return false;
	}
	return false;
}
 
Example #2
Source File: HttpTransportFactory.java    From hadoop-connectors with Apache License 2.0 7 votes vote down vote up
/**
 * Create an {@link ApacheHttpTransport} for calling Google APIs with an optional HTTP proxy.
 *
 * @param proxyUri Optional HTTP proxy URI to use with the transport.
 * @param proxyCredentials Optional HTTP proxy credentials to authenticate with the transport
 *     proxy.
 * @return The resulting HttpTransport.
 * @throws IOException If there is an issue connecting to Google's certification server.
 * @throws GeneralSecurityException If there is a security issue with the keystore.
 */
public static ApacheHttpTransport createApacheHttpTransport(
    @Nullable URI proxyUri, @Nullable Credentials proxyCredentials)
    throws IOException, GeneralSecurityException {
  checkArgument(
      proxyUri != null || proxyCredentials == null,
      "if proxyUri is null than proxyCredentials should be null too");

  ApacheHttpTransport transport =
      new ApacheHttpTransport.Builder()
          .trustCertificates(GoogleUtils.getCertificateTrustStore())
          .setProxy(
              proxyUri == null ? null : new HttpHost(proxyUri.getHost(), proxyUri.getPort()))
          .build();

  if (proxyCredentials != null) {
    ((DefaultHttpClient) transport.getHttpClient())
        .getCredentialsProvider()
        .setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()), proxyCredentials);
  }

  return transport;
}
 
Example #3
Source File: HttpClientUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static String httpPostWithWCF(String serverUrl, String method,
                                     JSONObject params) {
    String responseStr = null;
    try {
        String url = serverUrl + method;
        DefaultHttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost(url);

        request.setEntity(new StringEntity(params.toString(), CODE));
        request.setHeader(HTTP.CONTENT_TYPE, "text/json");

        HttpResponse response = client.execute(request);

        responseStr = EntityUtils.toString(response.getEntity(), CODE);
        // System.out.println("responseStr:" + responseStr);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseStr;
}
 
Example #4
Source File: SPARQLServiceTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
private boolean isExternalEndpointAvailable() throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    String url = "http://semantic.eea.europa.eu/sparql?query=";
    String query = "PREFIX rdfs:<http://www.w3.org/2000/01/rdf-schema#>\n"
            + "PREFIX cr:<http://cr.eionet.europa.eu/ontologies/contreg.rdf#>\n"
            + "SELECT * WHERE {  ?bookmark a cr:SparqlBookmark;rdfs:label ?label} LIMIT 50";
    url = url + URLEncoder.encode(query, "UTF-8");
    HttpGet httpGet = new HttpGet(url);
    httpClient.getParams().setParameter("http.socket.timeout", 300000);
    httpGet.setHeader("Accept", "text/xml");
    HttpResponse httpResponse = httpClient.execute(httpGet);
    if (httpResponse.getStatusLine().getStatusCode() == 200) {
        return true;
    }
    return false;
}
 
Example #5
Source File: TestServerBootstrapper.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private void invokeBootstrapExtension() throws ClientProtocolException, IOException {
  final String params = Common.BALANCED ? "?rs%3Abalanced=true" : "";

  DefaultHttpClient client = new DefaultHttpClient();

  client.getCredentialsProvider().setCredentials(
    new AuthScope(host, port),
    new UsernamePasswordCredentials(username, password));

  HttpPost post = new HttpPost("http://" + host + ":" + port
    + "/v1/resources/bootstrap" + params);

  HttpResponse response = client.execute(post);
  @SuppressWarnings("unused")
  HttpEntity entity = response.getEntity();
  System.out.println("Invoked bootstrap extension.  Response is "
    + response.toString());
}
 
Example #6
Source File: BitlyUrlService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Makes a GET request to the given address. Any query string should be appended already.
 * @param address	the fully qualified URL to make the request to
 * @return
 */
private String doGet(String address){
	try {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(address);
		HttpResponse response = httpclient.execute(httpget);
		
		//check reponse code
		StatusLine status = response.getStatusLine();
		if(status.getStatusCode() != 200) {
			log.error("Error shortening URL. Status: " + status.getStatusCode() + ", reason: " + status.getReasonPhrase());
			return null;
		}
		
		HttpEntity entity = response.getEntity();
		if (entity != null) {
		    return EntityUtils.toString(entity);
		}
		
	} catch (Exception e) {
		log.error(e.getClass() + ":" + e.getMessage());
	} 
	return null;
}
 
Example #7
Source File: WebAdminTest.java    From karyon with Apache License 2.0 6 votes vote down vote up
@Test
public void testRestEndPoints() throws Exception {
    HttpClient client = new DefaultHttpClient();
    for (Map.Entry<String, String> restEndPoint : REST_END_POINTS.entrySet()) {
        final String endPoint = restEndPoint.getKey();
        LOG.info("REST endpoint " + endPoint);
        HttpGet restGet = new HttpGet(endPoint);
        HttpResponse response = client.execute(restGet);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals(restEndPoint.getValue(), response.getEntity().getContentType().getValue());

        // need to consume full response before make another rest call with
        // the default SingleClientConnManager used with DefaultHttpClient
        EntityUtils.consume(response.getEntity());
    }
}
 
Example #8
Source File: InventoryIndexManagerImpl.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Override
public boolean start() {
    try {
        httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
        bulkUri = makeURI(elasticSearchBaseUrl, "_bulk");

        /* only for debugging */
        if (deleteAllIndexWhenStart) {
            try {
                deleteIndex(null);
            } catch (Exception ex) {
                logger.warn(String.format("Failed to delete all index"), ex);
            }
        }

        populateExtensions();
        populateTriggerVOs();
        populateInventoryIndexer();
        dumpInventoryIndexer();
        createIndexIfNotExists();
        bus.registerService(this);
    } catch (Exception e) {
        throw new CloudRuntimeException(e);
    }
    return true;
}
 
Example #9
Source File: OCTurnOff.java    From goprohero with MIT License 6 votes vote down vote up
public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}
 
Example #10
Source File: MainActivity.java    From speech-android-sdk with Apache License 2.0 6 votes vote down vote up
public String getToken() {

            Log.d(TAG, "attempting to get a token from: " + m_strTokenFactoryURL);
            try {
                // DISCLAIMER: the application developer should implement an authentication mechanism from the mobile app to the
                // server side app so the token factory in the server only provides tokens to authenticated clients
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(m_strTokenFactoryURL);
                HttpResponse executed = httpClient.execute(httpGet);
                InputStream is = executed.getEntity().getContent();
                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
                String strToken = writer.toString();
                Log.d(TAG, strToken);
                return strToken;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
 
Example #11
Source File: HttpAndroidClientFactory.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
public HttpClient createHttpClient(ClientConfiguration clientconfiguration)
{
    BasicHttpParams basichttpparams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(basichttpparams, clientconfiguration.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(basichttpparams, clientconfiguration.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(basichttpparams, true);
    HttpConnectionParams.setTcpNoDelay(basichttpparams, true);
    int i = clientconfiguration.getSocketBufferSizeHints()[0];
    int j = clientconfiguration.getSocketBufferSizeHints()[1];
    if (i > 0 || j > 0)
    {
        HttpConnectionParams.setSocketBufferSize(basichttpparams, Math.max(i, j));
    }
    SchemeRegistry schemeregistry = new SchemeRegistry();
    schemeregistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (clientconfiguration.getProtocol() == Protocol.HTTPS)
    {
        schemeregistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }
    return new DefaultHttpClient(new SingleClientConnManager(basichttpparams, schemeregistry), basichttpparams);
}
 
Example #12
Source File: HttpWrapper.java    From Android-Material-Icons with Apache License 2.0 6 votes vote down vote up
static String makeRequest(String uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri));
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            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 (IOException e) {
        e.printStackTrace();
    }
    return responseString;
}
 
Example #13
Source File: BuddycloudHTTPHelper.java    From buddycloud-android with Apache License 2.0 6 votes vote down vote up
public static void reqArrayNoSSL(String url, Context parent,
		ModelCallback<JSONArray> callback) {
	RequestAsyncTask<JSONArray> task = new RequestAsyncTask<JSONArray>(
			"get", url, null, false, false, parent, callback) {
		@Override
		protected JSONArray toJSON(String responseStr) throws JSONException {
			return new JSONArray(responseStr);
		}
	};
	task.client = new DefaultHttpClient();
	task.client.getParams().setParameter(
			ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	task.headers = new HashMap<String, String>();
	task.headers.put("User-Agent", BROWSER_LIKE_USER_AGENT);
	executeOnExecutor(task, HIGH_PRIORITY_EXECUTOR);
}
 
Example #14
Source File: StopActivity.java    From goprohero with MIT License 6 votes vote down vote up
public static String GET(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}
 
Example #15
Source File: ATLASUtil.java    From Criteria2Query with Apache License 2.0 6 votes vote down vote up
public static String getConcept(JSONObject jjj)
		throws UnsupportedEncodingException, IOException, ClientProtocolException {
	HttpPost httppost = new HttpPost(vocubularyurl);
	// httppost.setHeader("X-GWT-Permutation",
	// "3DE824138FE65400740EC1816A73CACC");
	httppost.setHeader("Content-Type", "application/json");
	StringEntity se = new StringEntity(jjj.toString());
	httppost.setEntity(se);
	startTime = System.currentTimeMillis();
	HttpResponse httpresponse = new DefaultHttpClient().execute(httppost);
	endTime = System.currentTimeMillis();
	System.out.println("statusCode:" + httpresponse.getStatusLine().getStatusCode());
	System.out.println("Call API time (unit:millisecond):" + (endTime - startTime));

	if (httpresponse.getStatusLine().getStatusCode() == 200) {
		// System.out.println("succeed!");
		String strResult = EntityUtils.toString(httpresponse.getEntity());
		return strResult;
		// httppost.
	} else {
		return null;
	}
}
 
Example #16
Source File: GridInfoExtractor.java    From selenium-grid2-api with Apache License 2.0 6 votes vote down vote up
public static GridInfo getHostNameAndPort(String hubHost, int hubPort, SessionId session) {

    GridInfo retVal = null;

    try {
      HttpHost host = new HttpHost(hubHost, hubPort);
      DefaultHttpClient client = new DefaultHttpClient();
      URL sessionURL = new URL("http://" + hubHost + ":" + hubPort + "/grid/api/testsession?session=" + session);
      BasicHttpEntityEnclosingRequest basicHttpEntityEnclosingRequest = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm());
      HttpResponse response = client.execute(host, basicHttpEntityEnclosingRequest);
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        JSONObject object = extractObject(response);
        retVal = new GridInfo(object);
      } else {
        System.out.println("Problem connecting to Grid Server");
      }
    } catch (JSONException | IOException  e) {
      throw new RuntimeException("Failed to acquire remote webdriver node and port info", e);
    }
    return retVal;
  }
 
Example #17
Source File: UpdateApp.java    From Popeens-DSub with GNU General Public License v3.0 6 votes vote down vote up
public String readJson(String url) {
    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
    return builder.toString();
}
 
Example #18
Source File: HTTP.java    From redalert-android with Apache License 2.0 6 votes vote down vote up
public static String get(String URL) throws Exception {
    // Get custom http client
    DefaultHttpClient client = getHTTPClient();

    // Create GET request
    HttpGet request = new HttpGet(URL);

    // Execute the request
    HttpResponse response = client.execute(request, new BasicHttpContext());

    // Return response as string
    String responseText = EntityUtils.toString(response.getEntity());

    // Failed?
    if (response.getStatusLine() == null || response.getStatusLine().getStatusCode() != 200) {
        // Throw it out
        throw new Exception(response.getStatusLine().toString() + "\n" + responseText);
    }

    // We're good
    return responseText;
}
 
Example #19
Source File: ESBJAVA5103CorrelateOnExpressionTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.esb", description = "Test CorrelateOn in Aggregate mediator ")
public void testAggregateWithCorrelateExpression() throws IOException{
    String expectedOutput1 = "<result><value>value1</value><value>value2</value></result>";
    String expectedOutput2 = "<result><value>value2</value><value>value1</value></result>";

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(getApiInvocationURL("testAggregate"));

    try {
        HttpResponse httpResponse = httpclient.execute(httpget);
        HttpEntity entity = httpResponse.getEntity();
        BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent()));
        String result = "";
        String line;
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        Assert.assertTrue(expectedOutput1.equals(result) || expectedOutput2.equals(result), "Aggregated response is not correct.");
    }
    finally {
        httpclient.clearRequestInterceptors();
    }
}
 
Example #20
Source File: RestFactory.java    From KubernetesAPIJavaClient with Apache License 2.0 5 votes vote down vote up
public KubernetesAPI createAPI(URI uri, String userName, String password) {

        // Configure HttpClient to authenticate preemptively
        // by prepopulating the authentication data cache.
        // http://docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html/RESTEasy_Client_Framework.html#transport_layer
        // http://hc.apache.org/httpcomponents-client-4.2.x/tutorial/html/authentication.html#d5e1032

        HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

        DefaultHttpClient httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(userName, password));

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

        // Add AuthCache to the execution context
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // 4. Create client executor and proxy
        ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, localcontext);
        ResteasyClient client = new ResteasyClientBuilder().connectionPoolSize(connectionPoolSize).httpEngine(engine)
                .build();

        client.register(JacksonJaxbJsonProvider.class).register(JacksonConfig.class);
        ProxyBuilder<KubernetesAPI> proxyBuilder = client.target(uri).proxyBuilder(KubernetesAPI.class);
        if (classLoader != null) {
            proxyBuilder = proxyBuilder.classloader(classLoader);
        }
        return proxyBuilder.build();
    }
 
Example #21
Source File: HttpClients.java    From flash-waimai with MIT License 5 votes vote down vote up
/**
 * 封装HTTP GET方法
 *
 * @param
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String get(String url) throws ClientProtocolException, IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpGet httpGet = new HttpGet();
	httpGet.setURI(URI.create(url));
	HttpResponse response = httpClient.execute(httpGet);
	String httpEntityContent = getHttpEntityContent(response);
	httpGet.abort();
	return httpEntityContent;
}
 
Example #22
Source File: ODataTenantUserTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private static int sendPOST(String endpoint, String content, String acceptType) throws IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httpPost = new HttpPost(endpoint);
	httpPost.setHeader("Accept", acceptType);
	if (null != content) {
		HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setEntity(httpEntity);
	}
	HttpResponse httpResponse = httpClient.execute(httpPost);
	return httpResponse.getStatusLine().getStatusCode();
}
 
Example #23
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Delete(final String uri) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpDelete del = new HttpDelete(uri);
    final HttpResponse response = client.execute(del);
    return response;
}
 
Example #24
Source File: ODataTestUtils.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public static Object[] sendPOST(String endpoint, String content, Map<String, String> headers) throws IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpPost httpPost = new HttpPost(endpoint);
	for (String headerType : headers.keySet()) {
		httpPost.setHeader(headerType, headers.get(headerType));
	}
	if (null != content) {
		HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
		if (headers.get("Content-Type") == null) {
			httpPost.setHeader("Content-Type", "application/json");
		}
		httpPost.setEntity(httpEntity);
	}
	HttpResponse httpResponse = httpClient.execute(httpPost);
	if (httpResponse.getEntity() != null) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
		String inputLine;
		StringBuilder response = new StringBuilder();

		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();
		return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
	} else {
		return new Object[] { httpResponse.getStatusLine().getStatusCode() };
	}
}
 
Example #25
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
public static void deleteElementRangeIndexTemporalCollection(String dbName, String collectionName)
		throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));

	HttpDelete del = new HttpDelete("http://" + host_name + ":" + admin_port + "/manage/v2/databases/" + dbName
			+ "/temporal/collections?collection=" + collectionName + "&format=json");

	del.addHeader("Content-type", "application/json");
	del.addHeader("accept", "application/json");

	HttpResponse response = client.execute(del);
	HttpEntity respEntity = response.getEntity();
	if (response.getStatusLine().getStatusCode() == 400) {
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseString);
	} else if (respEntity != null) {
		// EntityUtils to get the response content
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	} else {
		System.out.println("Collection: " + collectionName + " deleted");
		System.out.println("==============================================================");
	}
	client.getConnectionManager().shutdown();
}
 
Example #26
Source File: NetUtils.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
/**
 * post方式从服务器获取json数组
 * 
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 * @throws JSONException
 */
public static JSONArray getJSONArrayByPost(String uri)
		throws ClientProtocolException, IOException, JSONException {
	Log.i(TAG, "<getJSONArrayByPost> uri:" + uri, Log.APP);
	StringBuilder builder = new StringBuilder();
	HttpParams httpParameters = new BasicHttpParams();
	// Set the default socket timeout (SO_TIMEOUT) in milliseconds which is
	// the timeout for waiting for data.
	HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
	HttpConnectionParams.setSoTimeout(httpParameters, 10000);
	HttpClient client = new DefaultHttpClient(httpParameters);
	HttpPost post = new HttpPost(uri);

	HttpResponse response = client.execute(post);

	BufferedReader reader = new BufferedReader(new InputStreamReader(
			response.getEntity().getContent()));
	for (String s = reader.readLine(); s != null; s = reader.readLine()) {
		builder.append(s);
	}

	String jsonString = new String(builder.toString());

	if ("{}".equals(jsonString)) {
		return null;
	}
	Log.i(TAG, "<getJSONArrayByPost> jsonString:" + jsonString, Log.DATA);
	return new JSONArray(jsonString);
}
 
Example #27
Source File: AbstractWebIT.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void createClient(String ctxPath) throws Exception {
  testProperties = new TestProperties();

  APP_BASE_PATH = testProperties.getApplicationPath("/" + ctxPath);
  LOGGER.info("Connecting to application "+APP_BASE_PATH);

  ClientConfig clientConfig = new DefaultApacheHttpClient4Config();
  clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
  client = ApacheHttpClient4.create(clientConfig);

  defaultHttpClient = (DefaultHttpClient) client.getClientHandler().getHttpClient();
  HttpParams params = defaultHttpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(params, 3 * 60 * 1000);
  HttpConnectionParams.setSoTimeout(params, 10 * 60 * 1000);
}
 
Example #28
Source File: Client.java    From hbase with Apache License 2.0 5 votes vote down vote up
private void initialize(Cluster cluster, boolean sslEnabled) {
  this.cluster = cluster;
  this.sslEnabled = sslEnabled;
  extraHeaders = new ConcurrentHashMap<>();
  String clspath = System.getProperty("java.class.path");
  LOG.debug("classpath " + clspath);
  this.httpClient = new DefaultHttpClient();
  this.httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
}
 
Example #29
Source File: HttpServiceImpl.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse Get(final String uri, final String username, final String password) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    client.setRedirectStrategy(new LaxRedirectStrategy());
    final HttpGet get = new HttpGet(uri);
    final HttpResponse response = client.execute(get);

    return response;
    // TODO Return something useful maybe... like an InputStream
}
 
Example #30
Source File: util.java    From HomeApplianceMall with MIT License 5 votes vote down vote up
public static String getHttpJsonByhttpclient(String fromurl)
{
	System.out.print("------getHttpJsonByhttpclient------3-------");
	try{
		Log.v("zms","使用httget");
		HttpGet geturl=new HttpGet(fromurl);
		DefaultHttpClient httpclient=new DefaultHttpClient();
		HttpResponse response=httpclient.execute(geturl);
		Log.v("zms","响应码"+response.getStatusLine().getStatusCode());

		if (response.getStatusLine().getStatusCode()==200)
		{

			String returnStr= EntityUtils.toString(response.getEntity(),"utf-8");
			Log.v("zms","返回值"+returnStr);
			return returnStr;
		} else
		{
			Log.v("zms","访问网络返回数据失败,错误码:"+response.getStatusLine().getStatusCode());
		}

	}
	catch(IOException e)
	{
		e.printStackTrace();
	}
	return null;

}