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

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Amantech, under directory /Android/CloudAppStudioAndroid/src/com/cloudappstudio/utility/.

Source file: CloudOAuth.java

  37 
vote

public String getContent(String apiUrl) throws IllegalStateException, IOException {
  DefaultHttpClient httpClient=new DefaultHttpClient();
  BasicHttpParams params=new BasicHttpParams();
  HttpClientParams.setRedirecting(params,false);
  httpClient.setParams(params);
  HttpGet httpget=new HttpGet(apiUrl + "?userInfoOAuth=" + id.getToken());
  HttpResponse response=httpClient.execute(httpget);
  Log.d("debug","" + response.getStatusLine().getStatusCode());
  Log.d("debug","" + response.getStatusLine());
  return this.readTextFromHttpResponse(response);
}
 

Example 2

From project android-rackspacecloud, under directory /extensions/apachehc/src/main/java/org/jclouds/http/apachehc/config/.

Source file: ApacheHCHttpCommandExecutorServiceModule.java

  36 
vote

@Provides @Singleton HttpClient newDefaultHttpClient(HttpUtils utils,BasicHttpParams params,ClientConnectionManager cm){
  DefaultHttpClient client=new DefaultHttpClient(cm,params);
  if (utils.useSystemProxies()) {
    ProxySelectorRoutePlanner routePlanner=new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault());
    client.setRoutePlanner(routePlanner);
  }
  return client;
}
 

Example 3

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.

Source file: RequestHandler.java

  36 
vote

public static DefaultHttpClient getThreadSafeClient(){
  DefaultHttpClient client=new DefaultHttpClient();
  ClientConnectionManager mgr=client.getConnectionManager();
  HttpParams params=client.getParams();
  client=new DefaultHttpClient(new ThreadSafeClientConnManager(params,mgr.getSchemeRegistry()),params);
  return client;
}
 

Example 4

From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/dao/.

Source file: ScreenScrapingService.java

  36 
vote

/** 
 * Get HTML content for the specified dining hall.
 * @param diningHall
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
protected String getHtmlContent(String url) throws ClientProtocolException, IOException {
  final DefaultHttpClient httpclient=new DefaultHttpClient();
  final HttpGet httpget=new HttpGet(url);
  final HttpResponse response=httpclient.execute(httpget);
  final InputStream httpStream=response.getEntity().getContent();
  final String content=IOUtils.toString(httpStream);
  return content;
}
 

Example 5

From project CheckIn4Me, under directory /src/com/davidivins/checkin4me/oauth/.

Source file: OAuth2Request.java

  36 
vote

/** 
 * getTolerantClient Stolen from stackoverflow.com http://stackoverflow.com/questions/3135679/android-httpclient-hostname-in-certificate-didnt-match-example-com-exa
 * @return DefaultttpClient
 */
public DefaultHttpClient getTolerantClient(){
  DefaultHttpClient client=new DefaultHttpClient();
  SSLSocketFactory sslSocketFactory=(SSLSocketFactory)client.getConnectionManager().getSchemeRegistry().getScheme("https").getSocketFactory();
  final X509HostnameVerifier delegate=sslSocketFactory.getHostnameVerifier();
  if (!(delegate instanceof TolerantVerifier))   sslSocketFactory.setHostnameVerifier(new TolerantVerifier(delegate));
  return client;
}
 

Example 6

From project droidgiro-android, under directory /src/se/droidgiro/scanner/.

Source file: CloudClient.java

  36 
vote

public static boolean postFields(List<NameValuePair> fields) throws Exception {
  DefaultHttpClient client=new DefaultHttpClient();
  URI uri=new URI(INVOICES_URL);
  Log.e(TAG,"" + uri.toString());
  HttpPost post=new HttpPost(uri);
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(fields,"UTF-8");
  post.setEntity(entity);
  HttpResponse res=client.execute(post);
  return (res.getStatusLine().getStatusCode() == 201 ? true : false);
}
 

Example 7

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-httpdiscoveryproxy/src/main/java/org/easysoa/proxy/test/.

Source file: HttpUtils.java

  36 
vote

/** 
 * A simple GET Http call to the url
 * @param url
 * @return 
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String doGet(String url) throws ClientProtocolException, IOException {
  ResponseHandler<String> responseHandler=new BasicResponseHandler();
  DefaultHttpClient httpProxyClient=new DefaultHttpClient();
  HttpHost proxy=new HttpHost("localhost",EasySOAConstants.HTTP_DISCOVERY_PROXY_PORT);
  httpProxyClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  return httpProxyClient.execute(new HttpGet(url),responseHandler);
}
 

Example 8

From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.

Source file: HttpClientSingleton.java

  35 
vote

public static HttpClient getInstance(){
  if (instance == null) {
    instance=new DefaultHttpClient();
    HttpParams httpParams=instance.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,Values.TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams,Values.TIMEOUT);
  }
  return instance;
}
 

Example 9

From project Absolute-Android-RSS, under directory /src/com/AA/Other/.

Source file: RSSParse.java

  35 
vote

/** 
 * Get the XML document for the RSS feed
 * @return the XML Document for the feed on success, on error returns null
 */
private static Document getDocument(){
  Document doc=null;
  try {
    DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder();
    DefaultHttpClient client=new DefaultHttpClient();
    HttpGet request=new HttpGet(URI);
    HttpResponse response=client.execute(request);
    doc=builder.parse(response.getEntity().getContent());
  }
 catch (  java.io.IOException e) {
    return null;
  }
catch (  SAXException e) {
    Log.e("AARSS","Parse Exception in RSS feed",e);
    return null;
  }
catch (  Exception e) {
    return null;
  }
  return doc;
}
 

Example 10

From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.

Source file: SGS.java

  35 
vote

public SGS(){
  client=new DefaultHttpClient();
  HttpProtocolParams.setUserAgent(client.getParams(),"Mozilla/5.0 (X11; U; Linux x86_64; es-CL; rv:1.9.2.12) Gecko/20101027 Ubuntu/10.10 (maverick) Firefox/3.6.12");
  HttpProtocolParams.setVersion(client.getParams(),HttpVersion.HTTP_1_0);
  cleaner=new HtmlCleaner();
}
 

Example 11

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  35 
vote

private <T>HttpResult<T> doRequest(HttpUriRequest request,Type target){
  DefaultHttpClient client=new DefaultHttpClient();
  HttpResult<T> result=new HttpResult<T>();
  Reader reader=null;
  InputStream content=null;
  String fullJson=null;
  try {
    client.addRequestInterceptor(preemptiveAuth(),0);
    HttpResponse response=client.execute(request);
    content=response.getEntity().getContent();
    reader=new InputStreamReader(content);
    if (Constants.isDevMode()) {
      List<String> strings=CharStreams.readLines(reader);
      fullJson=Joiner.on("\n").join(strings);
      reader=new StringReader(fullJson);
    }
    T output=gson.fromJson(reader,target);
    result.setContent(output);
    result.setStatus(response.getStatusLine().getStatusCode() < 300 ? Status.SUCCESS : Status.FAILURE);
  }
 catch (  Exception e) {
    Log.e(Constants.TAG,"Http request failed",e);
    result.setStatus(Status.ERROR);
    return result;
  }
 finally {
    closeQuietly(content);
    closeQuietly(reader);
    client.getConnectionManager().shutdown();
  }
  return result;
}
 

Example 12

From project airlift, under directory /http-client/src/main/java/io/airlift/http/client/.

Source file: ApacheHttpClient.java

  35 
vote

public ApacheHttpClient(HttpClientConfig config,Set<HttpRequestFilter> requestFilters){
  Preconditions.checkNotNull(config,"config is null");
  Preconditions.checkNotNull(requestFilters,"requestFilters is null");
  PoolingClientConnectionManager connectionManager=new PoolingClientConnectionManager();
  connectionManager.setMaxTotal(config.getMaxConnections());
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerServer());
  BasicHttpParams httpParams=new BasicHttpParams();
  httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT,(int)config.getReadTimeout().toMillis());
  httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,(int)config.getConnectTimeout().toMillis());
  httpParams.setParameter(CoreConnectionPNames.SO_LINGER,0);
  this.httpClient=new DefaultHttpClient(connectionManager,httpParams);
  this.requestFilters=ImmutableList.copyOf(requestFilters);
}
 

Example 13

From project Airports, under directory /src/com/nadmm/airports/.

Source file: DownloadActivity.java

  35 
vote

private int downloadManifest(){
  try {
    if (!NetworkUtils.isNetworkAvailable(mActivity)) {
      UiUtils.showToast(mActivity,"Please check your network connection");
      return -1;
    }
    DefaultHttpClient httpClient=new DefaultHttpClient();
    File manifest=new File(getCacheDir(),MANIFEST);
    boolean fetch=true;
    if (manifest.exists()) {
      Date now=new Date();
      long age=now.getTime() - manifest.lastModified();
      if (age < 10 * DateUtils.MINUTE_IN_MILLIS) {
        fetch=false;
      }
    }
    if (fetch) {
      NetworkUtils.doHttpGet(mActivity,httpClient,HOST,PORT,PATH + "/" + MANIFEST,"uuid=" + UUID.randomUUID().toString(),manifest);
    }
  }
 catch (  Exception e) {
    UiUtils.showToast(mActivity,e.getMessage());
    return -1;
  }
  return 0;
}
 

Example 14

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/client/.

Source file: LogUploader.java

  35 
vote

/** 
 * Upload certain log to server.
 * @param testMethodId the ID of test method which log will be uploaded 
 * @param logFile - instance of file to upload 
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void upload(long testMethodId,File logFile) throws ClientProtocolException, IOException {
  String url=server + "/results/test-method/" + testMethodId+ "/log";
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url);
  MultipartEntity mpEntity=new MultipartEntity();
  ContentBody cbFile=new FileBody(logFile);
  mpEntity.addPart("fileData",cbFile);
  httppost.setEntity(mpEntity);
  httpclient.execute(httppost);
}
 

Example 15

From project and-bible, under directory /jsword-tweaks/src/main/java/jsword/org/crosswire/common/util/.

Source file: WebResource.java

  35 
vote

/** 
 * Construct a WebResource for the given URL, going through the optional proxy and port, while timing out if too much time has passed.
 * @param theURI the Resource to get via HTTP
 * @param theProxyHost the proxy host or null
 * @param theProxyPort the proxy port or null, where null means use the standard port
 * @param theTimeout the length of time in milliseconds to allow a connection to respond before timing out
 */
public WebResource(URI theURI,String theProxyHost,Integer theProxyPort,int theTimeout){
  uri=theURI;
  client=new DefaultHttpClient();
  HttpParams params=client.getParams();
  HttpConnectionParams.setSoTimeout(params,theTimeout);
  HttpConnectionParams.setConnectionTimeout(params,theTimeout);
  if (theProxyHost != null && theProxyHost.length() > 0) {
    HttpHost proxy=new HttpHost(theProxyHost,theProxyPort == null ? -1 : theProxyPort.intValue());
    ConnRouteParams.setDefaultProxy(params,proxy);
    ProxySelectorRoutePlanner routePlanner=new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),ProxySelector.getDefault());
    ((AbstractHttpClient)client).setRoutePlanner(routePlanner);
  }
}
 

Example 16

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: CatchAPI.java

  35 
vote

private HttpClient getHttpClientNoToken(){
  if (httpClientNoToken == null) {
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params,userAgent);
    HttpProtocolParams.setContentCharset(params,"UTF-8");
    httpClientNoToken=new DefaultHttpClient(params);
  }
  return httpClientNoToken;
}
 

Example 17

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  35 
vote

/** 
 * initialize the general property fields
 */
private void initialize(){
  client=new DefaultHttpClient();
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,10000);
  HttpConnectionParams.setSoTimeout(params,20000);
  client.setParams(params);
}
 

Example 18

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/puny/android/network/util/.

Source file: DrupalJSONServerNetworkUtilityBase.java

  35 
vote

/** 
 * Configures the httpClient to connect to the URL provided.
 */
public static void maybeCreateHttpClient(){
  if (mHttpClient == null) {
    mHttpClient=new DefaultHttpClient();
    final HttpParams params=mHttpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params,REGISTRATION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params,REGISTRATION_TIMEOUT);
    ConnManagerParams.setTimeout(params,REGISTRATION_TIMEOUT);
  }
}
 

Example 19

From project android-tether, under directory /src/og/android/tether/.

Source file: C2DMReceiver.java

  35 
vote

@Override public void onMessage(Context context,Intent intent){
  Bundle extras=intent.getExtras();
  if (extras != null) {
    Log.d(TAG,"Received message: " + extras.toString());
    String msg=(String)extras.get("msg");
    String title=(String)extras.get("title");
    String uid=(String)extras.get("uid");
    DefaultHttpClient client=new DefaultHttpClient();
    HttpGet get=new HttpGet(DeviceRegistrar.RECEIVED_PATH + "?uid=" + uid);
    try {
      client.execute(get);
    }
 catch (    ClientProtocolException e) {
    }
catch (    IOException e) {
    }
    String url=DeviceRegistrar.REACT_PATH + "?uid=" + uid;
    Intent launchIntent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    generateNotification(context,msg,title,launchIntent);
  }
}
 

Example 20

From project androidquery, under directory /demo/src/com/androidquery/test/async/.

Source file: AjaxLoadingActivity.java

  35 
vote

public void async_status(){
  String url="http://www.google.com/uds/GnewsSearch?q=Obama&v=1.0";
  aq.progress(R.id.progress).ajax(url,JSONObject.class,new AjaxCallback<JSONObject>(){
    @Override public void callback(    String url,    JSONObject json,    AjaxStatus status){
      int source=status.getSource();
      int responseCode=status.getCode();
      long duration=status.getDuration();
      Date fetchedTime=status.getTime();
      String message=status.getMessage();
      String redirect=status.getRedirect();
      DefaultHttpClient client=status.getClient();
      Map<String,Object> map=new HashMap<String,Object>();
      map.put("source",source);
      map.put("response code",responseCode);
      map.put("duration",duration);
      map.put("object fetched time",fetchedTime);
      map.put("message",message);
      map.put("redirect",redirect);
      map.put("client",client);
      showResult(map,status);
    }
  }
);
}
 

Example 21

From project Android_1, under directory /GsonJsonWebservice/src/com/novoda/activity/.

Source file: JsonRequest.java

  35 
vote

private InputStream retrieveStream(String url){
  DefaultHttpClient client=new DefaultHttpClient();
  HttpGet getRequest=new HttpGet(url);
  try {
    HttpResponse getResponse=client.execute(getRequest);
    final int statusCode=getResponse.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
      Log.w(getClass().getSimpleName(),"Error " + statusCode + " for URL "+ url);
      return null;
    }
    HttpEntity getResponseEntity=getResponse.getEntity();
    return getResponseEntity.getContent();
  }
 catch (  IOException e) {
    getRequest.abort();
    Log.w(getClass().getSimpleName(),"Error for URL " + url,e);
  }
  return null;
}
 

Example 22

From project android_7, under directory /src/org/immopoly/android/helper/.

Source file: WebHelper.java

  35 
vote

private static HttpResponse postHttp(String url,JSONObject jsonObject) throws ClientProtocolException, IOException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url);
  httppost.setHeader("User-Agent","immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
  httppost.setHeader("Accept-Encoding","gzip");
  HttpEntity entity;
  entity=new StringEntity(jsonObject.toString());
  httppost.setEntity(entity);
  return httpclient.execute(httppost);
}
 

Example 23

From project android_external_oauth, under directory /core/src/main/java/net/oauth/client/httpclient4/.

Source file: HttpClient4.java

  35 
vote

SingleClient(){
  HttpClient client=new DefaultHttpClient();
  ClientConnectionManager mgr=client.getConnectionManager();
  if (!(mgr instanceof ThreadSafeClientConnManager)) {
    HttpParams params=client.getParams();
    client=new DefaultHttpClient(new ThreadSafeClientConnManager(params,mgr.getSchemeRegistry()),params);
  }
  this.client=client;
}
 

Example 24

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasSyncService.java

  35 
vote

private HttpClient getHttpClient(int timeout){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,CONNECTION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,timeout);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpClient client=new DefaultHttpClient(getClientConnectionManager(),params);
  return client;
}
 

Example 25

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/media/.

Source file: UriTexture.java

  35 
vote

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,ClientConnectionManager connectionManager){
  InputStream contentInput=null;
  if (connectionManager == null) {
    try {
      URL url=new URI(uri).toURL();
      URLConnection conn=url.openConnection();
      conn.connect();
      contentInput=conn.getInputStream();
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + uri);
      e.printStackTrace();
      return null;
    }
  }
 else {
    final DefaultHttpClient mHttpClient=new DefaultHttpClient(connectionManager,HTTP_PARAMS);
    HttpUriRequest request=new HttpGet(uri);
    HttpResponse httpResponse=null;
    try {
      httpResponse=mHttpClient.execute(request);
      HttpEntity entity=httpResponse.getEntity();
      if (entity != null) {
        contentInput=entity.getContent();
      }
    }
 catch (    Exception e) {
      Log.w(TAG,"Request failed: " + request.getURI());
      return null;
    }
  }
  if (contentInput != null) {
    return new BufferedInputStream(contentInput,4096);
  }
 else {
    return null;
  }
}
 

Example 26

From project android_packages_apps_QuickSearchBox, under directory /src/com/android/quicksearchbox/google/.

Source file: GoogleSuggestClient.java

  35 
vote

public GoogleSuggestClient(Context context){
  super(context);
  mHttpClient=new DefaultHttpClient();
  HttpParams params=mHttpClient.getParams();
  HttpProtocolParams.setUserAgent(params,USER_AGENT);
  params.setLongParameter(HTTP_TIMEOUT,HTTP_TIMEOUT_MS);
  mSuggestUri=null;
}
 

Example 27

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  35 
vote

public static void postReport(URL url,String param) throws IOException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url.toExternalForm());
  try {
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("report",param));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpclient.execute(httppost);
  }
 catch (  ClientProtocolException e) {
    throw new IOException(e.getMessage());
  }
}
 

Example 28

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: AnkiDroidProxy.java

  35 
vote

public String getDecks(){
  String decksServer="{}";
  try {
    String data="p=" + URLEncoder.encode(mPassword,"UTF-8") + "&client=ankidroid-0.4&u="+ URLEncoder.encode(mUsername,"UTF-8")+ "&d=None&sources="+ URLEncoder.encode("[]","UTF-8")+ "&libanki=0.9.9.8.6&pversion=5";
    HttpPost httpPost=new HttpPost(SYNC_URL + "getDecks");
    StringEntity entity=new StringEntity(data);
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept-Encoding","identity");
    httpPost.setHeader("Content-type","application/x-www-form-urlencoded");
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpResponse response=httpClient.execute(httpPost);
    Log.i(AnkiDroidApp.TAG,"Response = " + response.toString());
    HttpEntity entityResponse=response.getEntity();
    Log.i(AnkiDroidApp.TAG,"Entity's response = " + entityResponse.toString());
    InputStream content=entityResponse.getContent();
    Log.i(AnkiDroidApp.TAG,"Content = " + content.toString());
    decksServer=Utils.convertStreamToString(new InflaterInputStream(content));
    Log.i(AnkiDroidApp.TAG,"String content = " + decksServer);
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    Log.i(AnkiDroidApp.TAG,"ClientProtocolException = " + e.getMessage());
  }
catch (  IOException e) {
    Log.i(AnkiDroidApp.TAG,"IOException = " + e.getMessage());
  }
  return decksServer;
}
 

Example 29

From project apps-for-android, under directory /Photostream/src/com/google/android/photostream/.

Source file: Flickr.java

  35 
vote

private void Flickr(){
  final HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,"UTF-8");
  final SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  final ThreadSafeClientConnManager manager=new ThreadSafeClientConnManager(params,registry);
  mClient=new DefaultHttpClient(manager,params);
}
 

Example 30

From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  35 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 31

From project Axon-trader, under directory /external-listeners/src/main/java/org/axonframework/samples/trader/listener/.

Source file: OrderbookExternalListener.java

  35 
vote

private void doHandle(TradeExecutedEvent event) throws IOException {
  String jsonObjectAsString=createJsonInString(event);
  HttpPost post=new HttpPost(remoteServerUri);
  post.setEntity(new StringEntity(jsonObjectAsString));
  post.addHeader("Content-Type","application/json");
  HttpClient client=new DefaultHttpClient();
  HttpResponse response=client.execute(post);
  if (response.getStatusLine().getStatusCode() != 200) {
    Writer writer=new StringWriter();
    IOUtils.copy(response.getEntity().getContent(),writer);
    logger.warn("Error while sending event to external system: {}",writer.toString());
  }
}
 

Example 32

From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.

Source file: ACSAuthenticationHelper.java

  35 
vote

/** 
 * Get OAuth SWT token from ACS
 */
private String getTokenFromACS(String acsNamespace,String acsMgmtPassword){
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(String.format(ACSAuthenticationHelper.AcsTokenServiceUrl,acsNamespace));
    List<NameValuePair> listNameValuePairs=new ArrayList<NameValuePair>();
    listNameValuePairs.add(new BasicNameValuePair("grant_type","client_credentials"));
    listNameValuePairs.add(new BasicNameValuePair("client_id",managementUserName));
    listNameValuePairs.add(new BasicNameValuePair("client_secret",acsMgmtPassword));
    listNameValuePairs.add(new BasicNameValuePair("scope",String.format(ACSAuthenticationHelper.AcsODataServiceUrl,acsNamespace)));
    UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(listNameValuePairs);
    httpPost.setEntity(formEntity);
    HttpResponse httpResponse=httpClient.execute(httpPost);
    HttpEntity entity=httpResponse.getEntity();
    InputStream inputStream=entity.getContent();
    InputStreamReader streamReader=new InputStreamReader(inputStream);
    BufferedReader bufferedReader=new BufferedReader(streamReader);
    String string=null;
    StringBuffer response=new StringBuffer();
    while ((string=bufferedReader.readLine()) != null) {
      response.append(string);
    }
    JSONObject obj=new JSONObject(response.toString());
    return obj.getString("access_token");
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 33

From project bbb-java, under directory /src/main/java/org/mconf/web/.

Source file: Authentication.java

  35 
vote

@SuppressWarnings("deprecation") public Authentication(String server,String username,String password) throws HttpException, IOException {
  this.server=server;
  SchemeRegistry registry=new SchemeRegistry();
  registry.register(new Scheme("http",new PlainSocketFactory(),80));
  registry.register(new Scheme("https",new FakeSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,false);
  client=new DefaultHttpClient(new ThreadSafeClientConnManager(params,registry),params);
  authenticated=authenticate(username,password);
}
 

Example 34

From project be.norio.twunch.android, under directory /src/be/norio/twunch/android/service/.

Source file: SyncService.java

  35 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 35

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/goodreads/.

Source file: GoodreadsManager.java

  35 
vote

/** 
 * Create an HttpClient with specifically set buffer sizes to deal with potentially exorbitant settings on some HTC handsets.
 * @return
 */
private HttpClient newHttpClient(){
  HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,30000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpConnectionParams.setLinger(params,0);
  HttpConnectionParams.setTcpNoDelay(params,false);
  HttpClient httpClient=new DefaultHttpClient(params);
  return httpClient;
}
 

Example 36

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: PreemptiveHttpClient.java

  35 
vote

private DefaultHttpClient createHttpClient(String userName,String password,int timeout){
  BasicHttpParams params=new BasicHttpParams();
  int timeoutMilliSeconds=timeout * 1000;
  HttpConnectionParams.setConnectionTimeout(params,timeoutMilliSeconds);
  HttpConnectionParams.setSoTimeout(params,timeoutMilliSeconds);
  DefaultHttpClient client=new DefaultHttpClient(params);
  if (userName != null && !"".equals(userName)) {
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),new UsernamePasswordCredentials(userName,password));
    localContext=new BasicHttpContext();
    BasicScheme basicAuth=new BasicScheme();
    localContext.setAttribute("preemptive-auth",basicAuth);
    client.addRequestInterceptor(new PreemptiveAuth(),0);
  }
  String userAgent="ArtifactoryBuildClient/" + CLIENT_VERSION;
  HttpProtocolParams.setUserAgent(client.getParams(),userAgent);
  return client;
}
 

Example 37

From project capedwarf-blue, under directory /urlfetch/src/main/java/org/jboss/capedwarf/urlfetch/.

Source file: JBossURLFetchService.java

  35 
vote

protected HttpClient getClient(){
  if (client == null) {
    SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",80,PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https",443,SSLSocketFactory.getSocketFactory()));
    HttpParams params=new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params,30 * 1000);
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,"UTF-8");
    ClientConnectionManager ccm=new ThreadSafeClientConnManager(schemeRegistry);
    client=new DefaultHttpClient(ccm,params);
  }
  return client;
}
 

Example 38

From project CHMI, under directory /src/org/kaldax/lib/net/app/netresource/.

Source file: ActualInfo.java

  35 
vote

private String getStringFromWebDoc(String strDocURL) throws IOException {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  HttpGet httpget=new HttpGet(strDocURL);
  HttpResponse response=httpclient.execute(httpget);
  HttpEntity entity=response.getEntity();
  if (response.getStatusLine().getStatusCode() != 200) {
    throw new IOException("HTTP error, code=" + new Integer(response.getStatusLine().getStatusCode()).toString());
  }
  InputStream inStream=entity.getContent();
  BufferedInputStream inBuffStream=new BufferedInputStream(inStream);
  StringBuffer fileData=new StringBuffer(1000);
  byte[] buf=new byte[1024];
  int numRead=0;
  while ((numRead=inBuffStream.read(buf)) != -1) {
    fileData.append(new String(buf),0,numRead);
  }
  inBuffStream.close();
  return fileData.toString();
}
 

Example 39

From project CineShowTime-Android, under directory /Libraries/CineShowTime/src/com/binomed/showtime/android/util/.

Source file: CineShowtimeFactory.java

  35 
vote

private HttpClient getClient(){
  if (client == null) {
    client=new DefaultHttpClient();
  }
  return client;
}
 

Example 40

From project CityBikes, under directory /src/net/homelinux/penecoptero/android/citybikes/app/.

Source file: RESTHelper.java

  35 
vote

public String restGET(String url) throws ClientProtocolException, IOException, HttpException {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  if (this.authenticated) {
    httpclient=this.setCredentials(httpclient,url);
  }
  HttpGet httpmethod=new HttpGet(url);
  HttpResponse response;
  String result=null;
  try {
    response=httpclient.execute(httpmethod);
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream instream=entity.getContent();
      result=convertStreamToString(instream);
      instream.close();
    }
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 41

From project Cloud-Shout, under directory /ckdgcloudshout-AppEngine/src/com/appspot/ckdgcloudshout/.

Source file: DownloadTest.java

  35 
vote

public static void main(String[] args){
  try {
    HttpResponse response=new DefaultHttpClient().execute(new HttpGet("http://localhost:8888/downloadmedia"));
    response.getStatusLine().getStatusCode();
    response.getAllHeaders();
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 42

From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/service/.

Source file: SyncService.java

  35 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 43

From project Core_2, under directory /shell/src/main/java/org/jboss/forge/shell/util/.

Source file: PluginUtil.java

  35 
vote

public static List<PluginRef> findPlugin(final Shell shell,Configuration config,final String searchString,boolean speak) throws Exception {
  String defaultRepo=getDefaultRepo(shell.getEnvironment());
  InputStream repoStream=getCachedRepoStream(getDefaultRepo(shell.getEnvironment()),shell.getEnvironment());
  if (repoStream == null) {
    HttpGet httpGet=new HttpGet(defaultRepo);
    if (speak)     shell.print("Connecting to remote repository [" + defaultRepo + "]... ");
    DefaultHttpClient client=new DefaultHttpClient();
    configureProxy(ProxySettings.fromForgeConfiguration(config),client);
    HttpResponse httpResponse=client.execute(httpGet);
switch (httpResponse.getStatusLine().getStatusCode()) {
case 200:
      if (speak)       shell.println("connected!");
    break;
case 404:
  if (speak)   shell.println("failed! (plugin index not found: " + defaultRepo + ")");
return Collections.emptyList();
default :
if (speak) shell.println("failed! (server returned status code: " + httpResponse.getStatusLine().getStatusCode());
return Collections.emptyList();
}
repoStream=httpResponse.getEntity().getContent();
setCachedRepoStream(defaultRepo,shell.getEnvironment(),repoStream);
repoStream=getCachedRepoStream(getDefaultRepo(shell.getEnvironment()),shell.getEnvironment());
}
return getPluginsFromRepoStream(searchString,repoStream);
}
 

Example 44

From project couchdb4j, under directory /src/java/com/fourspaces/couchdb/.

Source file: Session.java

  35 
vote

/** 
 * Constructor for obtaining a Session with an HTTP-AUTH username/password and (optionally) a secure connection This isn't supported by CouchDB - you need a proxy in front to use this
 * @param host - hostname
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param secure  - use an SSL connection?
 */
public Session(String host,int port,String user,String pass,boolean usesAuth,boolean secure){
  this.host=host;
  this.port=port;
  this.user=user;
  this.pass=pass;
  this.usesAuth=usesAuth;
  this.secure=secure;
  httpParams=new BasicHttpParams();
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ThreadSafeClientConnManager connManager=new ThreadSafeClientConnManager(httpParams,schemeRegistry);
  DefaultHttpClient defaultClient=new DefaultHttpClient(connManager,httpParams);
  if (user != null) {
    defaultClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(user,pass));
  }
  this.httpClient=defaultClient;
  setUserAgent("couchdb4j");
  setSocketTimeout((30 * 1000));
  setConnectionTimeout((15 * 1000));
}
 

Example 45

From project cow, under directory /src/com/ad/cow/library/.

Source file: JSONParser.java

  35 
vote

public JSONObject getJSONFromUrl(String url,List<NameValuePair> params){
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse httpResponse=httpClient.execute(httpPost);
    HttpEntity httpEntity=httpResponse.getEntity();
    is=httpEntity.getContent();
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  try {
    BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
    StringBuilder sb=new StringBuilder();
    String line=null;
    while ((line=reader.readLine()) != null) {
      sb.append(line + "n");
    }
    is.close();
    json=sb.toString();
    Log.e("JSON",json);
  }
 catch (  Exception e) {
    Log.e("Buffer Error","Error converting result " + e.toString());
  }
  try {
    jObj=new JSONObject(json);
  }
 catch (  JSONException e) {
    Log.e("JSON Parser","Error parsing data " + e.toString());
  }
  return jObj;
}
 

Example 46

From project crest, under directory /core/src/test/java/org/codegist/crest/io/http/.

Source file: HttpClientFactoryTest.java

  35 
vote

@Test public void createWithOneShouldCreateDefaultHttpClient() throws Exception {
  DefaultHttpClient expected=mock(DefaultHttpClient.class);
  ProxySelectorRoutePlanner planner=mock(ProxySelectorRoutePlanner.class);
  ClientConnectionManager clientConnectionManager=mock(ClientConnectionManager.class);
  SchemeRegistry schemeRegistry=mock(SchemeRegistry.class);
  ProxySelector proxySelector=mock(ProxySelector.class);
  when(expected.getConnectionManager()).thenReturn(clientConnectionManager);
  when(clientConnectionManager.getSchemeRegistry()).thenReturn(schemeRegistry);
  mockStatic(ProxySelector.class);
  when(ProxySelector.getDefault()).thenReturn(proxySelector);
  whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(expected);
  whenNew(ProxySelectorRoutePlanner.class).withArguments(schemeRegistry,proxySelector).thenReturn(planner);
  HttpClient actual=HttpClientFactory.create(crestConfig,getClass());
  assertSame(expected,actual);
  verify(expected).setRoutePlanner(planner);
}
 

Example 47

From project cw-advandroid, under directory /Honeycomb/WeatherFragment/src/com/commonsware/android/weather/.

Source file: WeatherBinder.java

  35 
vote

@Override protected ArrayList<Forecast> doInBackground(Location... locs){
  DefaultHttpClient client=new DefaultHttpClient();
  ArrayList<Forecast> result=null;
  try {
    Location loc=locs[0];
    String url=String.format(format,loc.getLatitude(),loc.getLongitude());
    HttpGet getMethod=new HttpGet(url);
    ResponseHandler<String> responseHandler=new BasicResponseHandler();
    String responseBody=client.execute(getMethod,responseHandler);
    result=buildForecasts(responseBody);
  }
 catch (  Exception e) {
    this.e=e;
  }
  client.getConnectionManager().shutdown();
  return (result);
}
 

Example 48

From project cw-android, under directory /Internet/Weather/src/com/commonsware/android/internet/.

Source file: WeatherDemo.java

  35 
vote

@Override public void onCreate(Bundle icicle){
  super.onCreate(icicle);
  setContentView(R.layout.main);
  mgr=(LocationManager)getSystemService(LOCATION_SERVICE);
  format=getString(R.string.url);
  browser=(WebView)findViewById(R.id.webkit);
  client=new DefaultHttpClient();
}
 

Example 49

From project CyborgFactoids, under directory /src/main/java/com/alta189/cyborg/factoids/util/.

Source file: HTTPUtil.java

  35 
vote

public static String readURL(String url){
  HttpGet request=new HttpGet(url);
  HttpClient httpClient=new DefaultHttpClient();
  try {
    HttpResponse response=httpClient.execute(request);
    return EntityUtils.toString(response.getEntity());
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 50

From project dccsched, under directory /src/com/underhilllabs/dccsched/service/.

Source file: SyncService.java

  35 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 51

From project dcnyc10-android, under directory /android/src/com/lullabot/android/apps/iosched/service/.

Source file: SyncService.java

  35 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSoTimeout(params,20 * SECOND_IN_MILLIS);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 52

From project DeliciousDroid, under directory /src/com/deliciousdroid/client/.

Source file: HttpClientFactory.java

  35 
vote

public static HttpClient getThreadSafeClient(){
  HttpParams params=new BasicHttpParams();
  ConnManagerParams.setMaxTotalConnections(params,100);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpConnectionParams.setConnectionTimeout(params,REGISTRATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,REGISTRATION_TIMEOUT);
  ConnManagerParams.setTimeout(params,REGISTRATION_TIMEOUT);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  ClientConnectionManager mgr=new ThreadSafeClientConnManager(params,schemeRegistry);
  HttpClient client=new DefaultHttpClient(mgr,params);
  return client;
}
 

Example 53

From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.

Source file: TickleServiceHelper.java

  35 
vote

static String getCookie(final Context context) throws ClientProtocolException, IOException, URISyntaxException {
  Settings settings=Settings.getInstance(context);
  final String authToken=settings.getString("web_connect_auth_token");
  if (authToken == null)   return null;
  Log.i(LOGTAG,authToken);
  Log.i(LOGTAG,"getting cookie");
  DefaultHttpClient client=new DefaultHttpClient();
  String continueURL=ServiceHelper.BASE_URL;
  URI uri=new URI(ServiceHelper.AUTH_URL + "?continue=" + URLEncoder.encode(continueURL,"UTF-8")+ "&auth="+ authToken);
  HttpGet method=new HttpGet(uri);
  final HttpParams getParams=new BasicHttpParams();
  HttpClientParams.setRedirecting(getParams,false);
  method.setParams(getParams);
  HttpResponse res=client.execute(method);
  Header[] headers=res.getHeaders("Set-Cookie");
  if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
    return null;
  }
  String ascidCookie=null;
  for (  Header header : headers) {
    if (header.getValue().indexOf("ACSID=") >= 0) {
      String value=header.getValue();
      String[] pairs=value.split(";");
      ascidCookie=pairs[0];
    }
  }
  settings.setString("Cookie",ascidCookie);
  return ascidCookie;
}
 

Example 54

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/service/.

Source file: RestService.java

  35 
vote

/** 
 * Generate and return a  {@link HttpClient} configured for general use,including setting an application-specific user-agent string.
 */
public static HttpClient getHttpClient(Context context){
  final HttpParams params=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(params,20 * 1000);
  HttpConnectionParams.setSoTimeout(params,20 * 1000);
  HttpConnectionParams.setSocketBufferSize(params,8192);
  HttpProtocolParams.setUserAgent(params,buildUserAgent(context));
  final DefaultHttpClient client=new DefaultHttpClient(params);
  client.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    HttpRequest request,    HttpContext context){
      if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
        request.addHeader(HEADER_ACCEPT_ENCODING,ENCODING_GZIP);
      }
    }
  }
);
  client.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    HttpResponse response,    HttpContext context){
      final HttpEntity entity=response.getEntity();
      final Header encoding=entity.getContentEncoding();
      if (encoding != null) {
        for (        HeaderElement element : encoding.getElements()) {
          if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
            response.setEntity(new InflatingEntity(response.getEntity()));
            break;
          }
        }
      }
    }
  }
);
  return client;
}
 

Example 55

From project DirectMemory, under directory /server/directmemory-server-client/src/main/java/org/apache/directmemory/server/client/providers/httpclient/.

Source file: HttpClientDirectMemoryHttpClient.java

  35 
vote

public void configure(DirectMemoryClientConfiguration configuration){
  this.configuration=configuration;
  ThreadSafeClientConnManager threadSafeClientConnManager=new ThreadSafeClientConnManager();
  threadSafeClientConnManager.setDefaultMaxPerRoute(configuration.getMaxConcurentConnections());
  this.httpClient=new DefaultHttpClient(threadSafeClientConnManager);
}
 

Example 56

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/helpers/.

Source file: SimpleHttpClient.java

  35 
vote

/** 
 * @param sp SharedPreferences of the Base-Context
 */
public SimpleHttpClient(){
  BasicHttpParams params=new BasicHttpParams();
  params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
  mDhc=new DefaultHttpClient(getEasySSLClientConnectionManager(),params);
  mContext=new BasicHttpContext();
  applyConfig();
}
 

Example 57

From project droidkit, under directory /src/org/droidkit/app/.

Source file: UpdateService.java

  35 
vote

private void queryServer(){
  DefaultHttpClient client=new DefaultHttpClient();
  HttpGet get=new HttpGet(mUpdateServer + "?foobar=boo");
  StringBuffer obj=new StringBuffer();
  Log.i("DroidKit","Checking updates: " + mUpdateServer);
  try {
    HttpResponse response=client.execute(get);
    InputStream in=response.getEntity().getContent();
    BufferedReader reader=new BufferedReader(new InputStreamReader(in),(int)response.getEntity().getContentLength());
    String line="";
    while ((line=reader.readLine()) != null) {
      obj.append(line);
      obj.append("\n");
    }
  }
 catch (  ClientProtocolException e) {
    Log.e("DroidKit","Error contacting update server: " + e.toString());
  }
catch (  IOException e) {
    Log.e("DroidKit","Error contacting update server: " + e.toString());
  }
  client.getConnectionManager().shutdown();
  parseJSONResponse(obj.toString());
}
 

Example 58

From project droidparts, under directory /extra/src/org/droidparts/http/wrapper/.

Source file: DefaultHttpClientWrapper.java

  35 
vote

public DefaultHttpClientWrapper(String userAgent){
  super(userAgent);
  httpClient=new DefaultHttpClient();
  HttpParams params=httpClient.getParams();
  HttpConnectionParams.setConnectionTimeout(params,SOCKET_OPERATION_TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,SOCKET_OPERATION_TIMEOUT);
  HttpConnectionParams.setSocketBufferSize(params,BUFFER_SIZE);
  if (userAgent != null) {
    HttpProtocolParams.setUserAgent(params,userAgent);
  }
}
 

Example 59

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/google/.

Source file: OAuthFlowApp.java

  35 
vote

private String doGet(String url,OAuthConsumer consumer) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  HttpGet request=new HttpGet(url);
  Log.i(TAG,"Requesting URL : " + url);
  consumer.sign(request);
  HttpResponse response=httpclient.execute(request);
  Log.i(TAG,"Statusline : " + response.getStatusLine());
  InputStream data=response.getEntity().getContent();
  BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(data));
  String responeLine;
  StringBuilder responseBuilder=new StringBuilder();
  while ((responeLine=bufferedReader.readLine()) != null) {
    responseBuilder.append(responeLine);
  }
  Log.i(TAG,"Response : " + responseBuilder.toString());
  return responseBuilder.toString();
}
 

Example 60

From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/.

Source file: HttpUtils.java

  34 
vote

public static HttpClient getNewHttpClient(){
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new EasySSLSocketFactory(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 61

From project accounted4, under directory /accounted4/stock-quote/stock-quote-yahoo/src/main/java/com/accounted4/stockquote/yahoo/.

Source file: YahooQuoteService.java

  34 
vote

@Override public List<HashMap<QuoteAttribute,String>> executeQuery(List<String> securityList,List<QuoteAttribute> quoteAttributes){
  String tickerList=securityListToString(securityList);
  String attributeList=attributeListToString(quoteAttributes);
  HttpClient httpclient=new DefaultHttpClient();
  String urlString=BASE_URL + "?" + "s="+ tickerList+ "&"+ "f="+ attributeList;
  System.out.println("Query url: " + urlString);
  HttpGet httpGet=new HttpGet(urlString);
  try {
    HttpResponse response=httpclient.execute(httpGet);
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      String stringResponse=EntityUtils.toString(entity);
      return processResponse(stringResponse,quoteAttributes);
    }
  }
 catch (  IOException ex) {
    System.out.println("Error " + ex);
  }
  List<HashMap<QuoteAttribute,String>> result=new ArrayList<>();
  return result;
}
 

Example 62

From project adg-android, under directory /src/com/analysedesgeeks/android/service/impl/.

Source file: DownloadServiceImpl.java

  34 
vote

@Override public boolean downloadFeed(){
  boolean downloadSuccess=false;
  if (connectionService.isConnected()) {
    InputStream inputStream=null;
    try {
      final HttpGet httpget=new HttpGet(new URI(Const.FEED_URL));
      final HttpResponse response=new DefaultHttpClient().execute(httpget);
      final StatusLine status=response.getStatusLine();
      if (status.getStatusCode() != HttpStatus.SC_OK) {
        Ln.e("Erreur lors du t??hargement:%s,%s",status.getStatusCode(),status.getReasonPhrase());
      }
 else {
        final HttpEntity entity=response.getEntity();
        inputStream=entity.getContent();
        final ByteArrayOutputStream content=new ByteArrayOutputStream();
        int readBytes=0;
        final byte[] sBuffer=new byte[512];
        while ((readBytes=inputStream.read(sBuffer)) != -1) {
          content.write(sBuffer,0,readBytes);
        }
        final String dataAsString=new String(content.toByteArray());
        final List<FeedItem> syndFeed=rssService.parseRss(dataAsString);
        if (syndFeed != null) {
          databaseService.save(dataAsString);
          downloadSuccess=true;
        }
      }
    }
 catch (    final Throwable t) {
      Ln.e(t);
    }
 finally {
      closeQuietly(inputStream);
    }
  }
  return downloadSuccess;
}
 

Example 63

From project ajah, under directory /ajah-http/src/main/java/com/ajah/http/.

Source file: Http.java

  34 
vote

private static HttpEntity internalGet(final URI uri) throws IOException, ClientProtocolException, NotFoundException, UnexpectedResponseCode {
  final HttpClient httpclient=new DefaultHttpClient();
  final HttpGet httpget=new HttpGet(uri);
  final HttpResponse response=httpclient.execute(httpget);
  if (response.getStatusLine().getStatusCode() == 200) {
    final HttpEntity entity=response.getEntity();
    return entity;
  }
 else   if (response.getStatusLine().getStatusCode() == 404) {
    throw new NotFoundException(response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
  }
 else {
    throw new UnexpectedResponseCode(response.getStatusLine().getStatusCode() + " - " + response.getStatusLine().getReasonPhrase());
  }
}
 

Example 64

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.

Source file: AVService.java

  34 
vote

@Override protected HttpResponse[] doInBackground(ArrayList<Object>... params){
  HttpResponse[] response=new HttpResponse[2];
  int i=0;
  for (  ArrayList<Object> PicArray : params) {
    if (PicArray != null) {
      HttpClient httpClient=new DefaultHttpClient();
      HttpContext localContext=new BasicHttpContext();
      HttpPost httpPost=new HttpPost((String)PicArray.get(0));
      httpPost.addHeader("udid",(String)PicArray.get(1));
      Log.d(Constants.PROJECT_TAG,"length : " + ((String)PicArray.get(2)).length());
      httpPost.addHeader("img_comment",(String)PicArray.get(2));
      httpPost.addHeader("incident_id",(String)PicArray.get(3));
      httpPost.addHeader("type",(String)PicArray.get(4));
      if (((Boolean)PicArray.get(6)).booleanValue()) {
        httpPost.addHeader("INCIDENT_CREATION","true");
      }
      try {
        FileEntity file=new FileEntity((File)PicArray.get(5),"image/jpeg");
        file.setContentType("image/jpeg");
        httpPost.setEntity(file);
        response[i++]=httpClient.execute(httpPost,localContext);
      }
 catch (      IOException e) {
        Log.e(Constants.PROJECT_TAG,"IOException postImage",e);
      }
catch (      IllegalStateException e) {
        Log.e(Constants.PROJECT_TAG,"IllegalStateException postImage",e);
      }
    }
  }
  return response;
}
 

Example 65

From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.

Source file: Chalmrest.java

  34 
vote

@Override public void update() throws BankException, LoginException, BankChoiceException {
  super.update();
  if (username == null || username.length() == 0)   throw new LoginException(res.getText(R.string.invalid_username_password).toString());
  try {
    String cardNr=username;
    HttpClient httpclient=new DefaultHttpClient();
    HttpGet httpget=new HttpGet("http://kortladdning.chalmerskonferens.se/bgw.aspx?type=getCardAndArticles&card=" + cardNr);
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    if (entity == null)     throw new BankException("Couldn't connect!");
    String s1=EntityUtils.toString(entity);
    Pattern pattern=Pattern.compile("<ExtendedInfo Name=\"Kortvarde\" Type=\"System.Double\" >(.*?)</ExtendedInfo>");
    Matcher matcher=pattern.matcher(s1);
    if (!matcher.find())     throw new BankException("Couldn't parse value!");
    String value=matcher.group(1);
    StringBuilder sb=new StringBuilder();
    int last=0;
    Matcher match=Pattern.compile("_x([0-9A-Fa-f]{4})_").matcher(value);
    while (match.find()) {
      sb.append(value.substring(last,Math.max(match.start() - 1,0)));
      int i=Integer.parseInt(match.group(1),16);
      sb.append((char)i);
      last=match.end();
    }
    sb.append(value.substring(last));
    value=sb.toString();
    matcher=Pattern.compile("<CardInfo id=\"" + cardNr + "\" Name=\"(.*?)\"").matcher(s1);
    if (!matcher.find())     throw new BankException("Coldn't parse name!");
    String name=matcher.group(1);
    accounts.add(new Account(name,BigDecimal.valueOf(Double.parseDouble(value)),"1"));
  }
 catch (  Exception e) {
    throw new BankException(e.getMessage());
  }
 finally {
    super.updateComplete();
  }
}
 

Example 66

From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.

Source file: RadioInfo.java

  34 
vote

/** 
 * This function checks for basic functionality of HTTP Client.
 */
private void httpClientTest(){
  HttpClient client=new DefaultHttpClient();
  try {
    HttpGet request=new HttpGet("http://www.google.com");
    HttpResponse response=client.execute(request);
    if (response.getStatusLine().getStatusCode() == 200) {
      mHttpClientTestResult="Pass";
    }
 else {
      mHttpClientTestResult="Fail: Code: " + String.valueOf(response);
    }
    request.abort();
  }
 catch (  IOException e) {
    mHttpClientTestResult="Fail: IOException";
  }
}
 

Example 67

From project andstatus, under directory /src/org/andstatus/app/net/.

Source file: ConnectionOAuth.java

  34 
vote

public ConnectionOAuth(MyAccount ma){
  super(ma);
  mOauthBaseUrl=ma.getOauthBaseUrl();
  HttpParams parameters=new BasicHttpParams();
  HttpProtocolParams.setVersion(parameters,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(parameters,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(parameters,false);
  HttpConnectionParams.setTcpNoDelay(parameters,true);
  HttpConnectionParams.setSocketBufferSize(parameters,8192);
  SchemeRegistry schReg=new SchemeRegistry();
  schReg.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  ClientConnectionManager tsccm=new ThreadSafeClientConnManager(parameters,schReg);
  mClient=new DefaultHttpClient(tsccm,parameters);
  OAuthKeys oak=new OAuthKeys(ma.getOriginId());
  mConsumer=new CommonsHttpOAuthConsumer(oak.getConsumerKey(),oak.getConsumerSecret());
  mProvider=new CommonsHttpOAuthProvider(getApiUrl(apiEnum.OAUTH_REQUEST_TOKEN),getApiUrl(apiEnum.OAUTH_ACCESS_TOKEN),getApiUrl(apiEnum.OAUTH_AUTHORIZE));
  mProvider.setOAuth10a(true);
  if (ma.dataContains(ConnectionOAuth.USER_TOKEN) && ma.dataContains(ConnectionOAuth.USER_SECRET)) {
    setAuthInformation(ma.getDataString(ConnectionOAuth.USER_TOKEN,null),ma.getDataString(ConnectionOAuth.USER_SECRET,null));
  }
}
 

Example 68

From project andtweet, under directory /src/com/xorcode/andtweet/net/.

Source file: ConnectionOAuth.java

  34 
vote

public ConnectionOAuth(SharedPreferences sp){
  super(sp);
  HttpParams parameters=new BasicHttpParams();
  HttpProtocolParams.setVersion(parameters,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(parameters,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(parameters,false);
  HttpConnectionParams.setTcpNoDelay(parameters,true);
  HttpConnectionParams.setSocketBufferSize(parameters,8192);
  SchemeRegistry schReg=new SchemeRegistry();
  schReg.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  ClientConnectionManager tsccm=new ThreadSafeClientConnManager(parameters,schReg);
  mClient=new DefaultHttpClient(tsccm,parameters);
  mConsumer=new CommonsHttpOAuthConsumer(OAuthKeys.TWITTER_CONSUMER_KEY,OAuthKeys.TWITTER_CONSUMER_SECRET);
  loadSavedKeys(sp);
}
 

Example 69

From project anode, under directory /app/src/org/meshpoint/anode/util/.

Source file: ModuleUtils.java

  34 
vote

public static File getResource(URI httpUri,String filename) throws IOException {
  HttpClient http=new DefaultHttpClient();
  HttpGet request=new HttpGet();
  request.setURI(httpUri);
  HttpEntity entity=http.execute(request).getEntity();
  InputStream in=entity.getContent();
  File destination=new File(resourceDir,filename);
  FileOutputStream out=new FileOutputStream(destination);
  byte[] buf=new byte[1024];
  int read;
  while ((read=in.read(buf)) != -1) {
    out.write(buf,0,read);
  }
  in.close();
  out.flush();
  out.close();
  return destination;
}
 

Example 70

From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/.

Source file: FileApiClientAdapterImpl.java

  34 
vote

private StringResponse executeHttpcall(HttpRequestBase httpRequest) throws FileApiException {
  HttpClient httpClient=null;
  try {
    httpClient=new DefaultHttpClient();
    setupProxy(httpClient);
    HttpResponse response=httpClient.execute(httpRequest);
    if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK)     return inputStreamToString(response.getEntity().getContent(),null);
    throw new FileApiException(inputStreamToString(response.getEntity().getContent(),null).getContents());
  }
 catch (  IOException e) {
    throw new FileApiException(e);
  }
 finally {
    if (null != httpClient)     httpClient.getConnectionManager().shutdown();
  }
}
 

Example 71

From project aranea, under directory /webapp/src/test/java/no/dusken/aranea/integration/test/.

Source file: AbstractIntegrationTest.java

  34 
vote

@Before public void before(){
  webDriver=new HtmlUnitDriver(false){
    @Override public WebElement findElement(    By by){
      WebElement element=super.findElement(by);
      checkValidity();
      return element;
    }
    @Override public List<WebElement> findElements(    By by){
      List<WebElement> elements=super.findElements(by);
      checkValidity();
      return elements;
    }
    @Override public String getPageSource(){
      Page page=lastPage();
      if (page == null) {
        return null;
      }
      WebResponse response=page.getWebResponse();
      return response.getContentAsString();
    }
  }
;
  webDriver.get(host);
  httpclient=new DefaultHttpClient();
  mapper=new ObjectMapper();
  allowedErrorMessages.add("Attribute property not allowed on element meta at this point.");
  allowedErrorMessages.add("Element meta is missing one or more of the following attributes: http-equiv, itemprop, name.");
  allowedErrorMessages.add("Element fb:like not allowed as child of element div in this context. (Suppressing further errors from this subtree.)");
}
 

Example 72

From project b3log-latke, under directory /latke-client/src/main/java/org/b3log/latke/client/.

Source file: LatkeClient.java

  34 
vote

/** 
 * Gets repository names.
 * @return repository names
 * @throws Exception exception
 */
private static Set<String> getRepositoryNames() throws Exception {
  final HttpClient httpClient=new DefaultHttpClient();
  final List<NameValuePair> qparams=new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("userName",userName));
  qparams.add(new BasicNameValuePair("password",password));
  final URI uri=URIUtils.createURI("http",serverAddress,-1,GET_REPOSITORY_NAMES,URLEncodedUtils.format(qparams,"UTF-8"),null);
  final HttpGet request=new HttpGet();
  request.setURI(uri);
  if (verbose) {
    System.out.println("Getting repository names[" + GET_REPOSITORY_NAMES + "]");
  }
  final HttpResponse httpResponse=httpClient.execute(request);
  final InputStream contentStream=httpResponse.getEntity().getContent();
  final String content=IOUtils.toString(contentStream).trim();
  if (verbose) {
    printResponse(content);
  }
  final JSONObject result=new JSONObject(content);
  final JSONArray repositoryNames=result.getJSONArray("repositoryNames");
  final Set<String> ret=new HashSet<String>();
  for (int i=0; i < repositoryNames.length(); i++) {
    final String repositoryName=repositoryNames.getString(i);
    ret.add(repositoryName);
    final File dir=new File(backupDir.getPath() + File.separatorChar + repositoryName);
    if (!dir.exists() && verbose) {
      dir.mkdir();
      System.out.println("Created a directory[name=" + dir.getName() + "] under backup directory[path="+ backupDir.getPath()+ "]");
    }
  }
  return ret;
}
 

Example 73

From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.

Source file: HttpSupport.java

  34 
vote

/** 
 * Make a POST request with the given Map of parameters to be encoded
 * @param address	address to POST to
 * @param params	Map of params to use as the form parameters
 * @return
 */
public static String doPost(String address,Map<String,String> params){
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpPost httppost=new HttpPost(address);
    List<NameValuePair> formparams=new ArrayList<NameValuePair>();
    for (    Map.Entry<String,String> entry : params.entrySet()) {
      formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
    }
    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,HTTP.UTF_8);
    httppost.setEntity(entity);
    HttpResponse response=httpclient.execute(httppost);
    String responseContent=EntityUtils.toString(response.getEntity());
    return responseContent;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    httpclient.getConnectionManager().shutdown();
  }
  return null;
}
 

Example 74

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: LoaderImageView.java

  34 
vote

private static Drawable getDrawableFromUrl(final String url) throws IOException, MalformedURLException {
  try {
    HttpGet httpRequest=new HttpGet(new URL(url).toURI());
    HttpClient httpClient=new DefaultHttpClient();
    HttpResponse response=(HttpResponse)httpClient.execute(httpRequest);
    HttpEntity entity=response.getEntity();
    BufferedHttpEntity bufHttpEntity=new BufferedHttpEntity(entity);
    final long contentLength=bufHttpEntity.getContentLength();
    if (contentLength >= 0) {
      InputStream is=bufHttpEntity.getContent();
      return Drawable.createFromStream(is,"name");
    }
 else {
      return null;
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 75

From project bitfluids, under directory /src/test/java/at/bitcoin_austria/bitfluids/.

Source file: NetTest.java

  34 
vote

public static HttpClient wrapClient(HttpClient base){
  try {
    SSLContext ctx=SSLContext.getInstance("TLS");
    X509TrustManager tm=new X509TrustManager(){
      @Override public void checkClientTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      @Override public void checkServerTrusted(      X509Certificate[] xcs,      String string) throws CertificateException {
      }
      @Override public X509Certificate[] getAcceptedIssuers(){
        return null;
      }
    }
;
    ctx.init(null,new TrustManager[]{tm},null);
    SSLSocketFactory ssf=new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm=base.getConnectionManager();
    SchemeRegistry sr=ccm.getSchemeRegistry();
    sr.register(new Scheme("https",ssf,443));
    return new DefaultHttpClient(ccm,base.getParams());
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 76

From project bookmarktodesktop-android-application, under directory /src/be/vbsteven/bmtodesk/.

Source file: BackgroundSharingService.java

  34 
vote

/** 
 * sends the bookmark to the server in a POST request
 * @param title
 * @param url
 */
private void sendToServer(final String title,final String url){
  showProgress();
  String username=Global.getUsername(BackgroundSharingService.this);
  String password=Global.getPassword(BackgroundSharingService.this);
  String responseMessage;
  try {
    HttpClient httpclient=new DefaultHttpClient();
    HttpPost post=new HttpPost(URI.create(URL));
    ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("username",username));
    nameValuePairs.add(new BasicNameValuePair("password",password));
    nameValuePairs.add(new BasicNameValuePair("title",title));
    nameValuePairs.add(new BasicNameValuePair("url",url));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response=httpclient.execute(post);
    BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
    responseMessage=reader.readLine();
  }
 catch (  Exception e) {
    responseMessage="REQUESTFAILED";
  }
  hideProgress();
  onResult(responseMessage);
}
 

Example 77

From project BusFollower, under directory /src/net/argilo/busfollower/ocdata/.

Source file: OCTranspoDataFetcher.java

  34 
vote

public GetNextTripsForStopResult getNextTripsForStop(String stopNumber,String routeNumber) throws IOException, XmlPullParserException, IllegalArgumentException {
  validateStopNumber(stopNumber);
  validateRouteNumber(routeNumber);
  httpClient=new DefaultHttpClient(getHttpParams());
  HttpPost post=new HttpPost("https://api.octranspo1.com/v1.1/GetNextTripsForStop");
  List<NameValuePair> params=new ArrayList<NameValuePair>(4);
  params.add(new BasicNameValuePair("appID",context.getString(R.string.oc_transpo_application_id)));
  params.add(new BasicNameValuePair("apiKey",context.getString(R.string.oc_transpo_application_key)));
  params.add(new BasicNameValuePair("routeNo",routeNumber));
  params.add(new BasicNameValuePair("stopNo",stopNumber));
  post.setEntity(new UrlEncodedFormEntity(params));
  HttpResponse response=httpClient.execute(post);
  XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
  factory.setNamespaceAware(true);
  XmlPullParser xpp=factory.newPullParser();
  InputStream in=response.getEntity().getContent();
  xpp.setInput(in,"UTF-8");
  xpp.next();
  xpp.next();
  xpp.next();
  xpp.next();
  GetNextTripsForStopResult result=new GetNextTripsForStopResult(context,db,xpp,stopNumber);
  in.close();
  return result;
}
 

Example 78

From project callmeter, under directory /src/de/ub0r/android/callmeter/ui/prefs/.

Source file: Preferences.java

  34 
vote

/** 
 * Get a  {@link InputStream} from {@link Uri}.
 * @param cr {@link ContentResolver}
 * @param uri {@link Uri}
 * @return {@link InputStream}
 */
private InputStream getStream(final ContentResolver cr,final Uri uri){
  if (uri.toString().equals("content://default")) {
    return IS_DEFAULT;
  }
 else   if (uri.toString().startsWith("import")) {
    String url;
    if (uri.getScheme().equals("imports")) {
      url="https:/";
    }
 else {
      url="http:/";
    }
    url+=uri.getPath();
    final HttpGet request=new HttpGet(url);
    Log.d(TAG,"url: " + url);
    try {
      final HttpResponse response=new DefaultHttpClient().execute(request);
      int resp=response.getStatusLine().getStatusCode();
      if (resp != HttpStatus.SC_OK) {
        return null;
      }
      return response.getEntity().getContent();
    }
 catch (    IOException e) {
      Log.e(TAG,"error in reading export: " + url,e);
      return null;
    }
  }
 else   if (uri.toString().startsWith("content://") || uri.toString().startsWith("file://")) {
    try {
      return cr.openInputStream(uri);
    }
 catch (    IOException e) {
      Log.e(TAG,"error in reading export: " + uri.toString(),e);
      return null;
    }
  }
  Log.d(TAG,"getStream() returns null, " + uri.toString());
  return null;
}
 

Example 79

From project cloudify, under directory /rest-client/src/main/java/org/cloudifysource/restclient/.

Source file: GSRestClient.java

  34 
vote

/** 
 * Ctor.
 * @param username Username for the HTTP client, optional.
 * @param password Password for the HTTP client, optional.
 * @param url      URL to the rest service.
 * @param version  cloudify api version of the client 
 * @throws RestException Reporting failure to create a SSL HTTP client.
 */
public GSRestClient(final String username,final String password,final URL url,final String version) throws RestException {
  this.url=url;
  this.urlStr=createUrlStr();
  if (isSSL()) {
    httpClient=getSSLHttpClient();
  }
 else {
    httpClient=new DefaultHttpClient();
  }
  httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
    @Override public void process(    HttpRequest request,    HttpContext context) throws HttpException, IOException {
      request.addHeader(CloudifyConstants.REST_API_VERSION_HEADER,version);
    }
  }
);
  if (StringUtils.notEmpty(username) && StringUtils.notEmpty(password)) {
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),new UsernamePasswordCredentials(username,password));
  }
}
 

Example 80

From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/.

Source file: HttpClientFactory.java

  34 
vote

public static synchronized HttpClient getInstance() throws MalformedURLException {
  if (instance == null) {
    final HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUseExpectContinue(params,false);
    HttpConnectionParams.setTcpNoDelay(params,true);
    HttpConnectionParams.setStaleCheckingEnabled(params,false);
    ConnManagerParams.setMaxTotalConnections(params,1000);
    ConnManagerParams.setMaxConnectionsPerRoute(params,new ConnPerRouteBean(1000));
    final SchemeRegistry schemeRegistry=new SchemeRegistry();
    schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),5984));
    schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
    final ClientConnectionManager cm=new ShieldedClientConnManager(new ThreadSafeClientConnManager(params,schemeRegistry));
    instance=new DefaultHttpClient(cm,params);
    if (INI != null) {
      final CredentialsProvider credsProvider=new BasicCredentialsProvider();
      final Iterator<?> it=INI.getKeys();
      while (it.hasNext()) {
        final String key=(String)it.next();
        if (!key.startsWith("lucene.") && key.endsWith(".url")) {
          final URL url=new URL(INI.getString(key));
          if (url.getUserInfo() != null) {
            credsProvider.setCredentials(new AuthScope(url.getHost(),url.getPort()),new UsernamePasswordCredentials(url.getUserInfo()));
          }
        }
      }
      instance.setCredentialsProvider(credsProvider);
      instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(),0);
    }
  }
  return instance;
}
 

Example 81

From project creamed_glacier_app_settings, under directory /src/com/android/settings/.

Source file: RadioInfo.java

  34 
vote

/** 
 * This function checks for basic functionality of HTTP Client.
 */
private void httpClientTest(){
  HttpClient client=new DefaultHttpClient();
  try {
    HttpGet request=new HttpGet("http://www.google.com");
    HttpResponse response=client.execute(request);
    if (response.getStatusLine().getStatusCode() == 200) {
      mHttpClientTestResult="Pass";
    }
 else {
      mHttpClientTestResult="Fail: Code: " + String.valueOf(response);
    }
    request.abort();
  }
 catch (  IOException e) {
    mHttpClientTestResult="Fail: IOException";
  }
}
 

Example 82

From project DiscogsForAndroid, under directory /src/com/discogs/services/.

Source file: NetworkHelper.java

  34 
vote

private void initHTTPClient(){
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  HttpParams params=new BasicHttpParams();
  HttpProtocolParams.setContentCharset(params,"utf-8");
  params.setBooleanParameter("http.protocol.expect-continue",false);
  HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setContentCharset(params,HTTP.DEFAULT_CONTENT_CHARSET);
  HttpProtocolParams.setUseExpectContinue(params,true);
  ThreadSafeClientConnManager connectionManager=new ThreadSafeClientConnManager(params,schemeRegistry);
  httpClient=new DefaultHttpClient(connectionManager,params);
  httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3,false));
  httpClient.addRequestInterceptor(new HttpRequestInterceptor(){
    public void process(    final HttpRequest request,    final HttpContext context) throws HttpException, IOException {
      if (!request.containsHeader("Accept-Encoding")) {
        request.addHeader("Accept-Encoding","gzip");
      }
    }
  }
);
  httpClient.addResponseInterceptor(new HttpResponseInterceptor(){
    public void process(    final HttpResponse response,    final HttpContext context) throws HttpException, IOException {
      HttpEntity entity=response.getEntity();
      if (entity != null) {
        Header ceheader=entity.getContentEncoding();
        if (ceheader != null) {
          HeaderElement[] codecs=ceheader.getElements();
          for (int i=0; i < codecs.length; i++) {
            if (codecs[i].getName().equalsIgnoreCase("gzip")) {
              response.setEntity(new GzipDecompressingEntity(response.getEntity()));
              return;
            }
          }
        }
      }
    }
  }
);
}
 

Example 83

From project droid-fu, under directory /src/main/java/com/github/droidfu/http/.

Source file: BetterHttp.java

  34 
vote

public static void setupHttpClient(){
  BasicHttpParams httpParams=new BasicHttpParams();
  ConnManagerParams.setTimeout(httpParams,socketTimeout);
  ConnManagerParams.setMaxConnectionsPerRoute(httpParams,new ConnPerRouteBean(maxConnections));
  ConnManagerParams.setMaxTotalConnections(httpParams,DEFAULT_MAX_CONNECTIONS);
  HttpConnectionParams.setSoTimeout(httpParams,socketTimeout);
  HttpConnectionParams.setTcpNoDelay(httpParams,true);
  HttpProtocolParams.setVersion(httpParams,HttpVersion.HTTP_1_1);
  HttpProtocolParams.setUserAgent(httpParams,httpUserAgent);
  SchemeRegistry schemeRegistry=new SchemeRegistry();
  schemeRegistry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
  if (DiagnosticSupport.ANDROID_API_LEVEL >= 7) {
    schemeRegistry.register(new Scheme("https",SSLSocketFactory.getSocketFactory(),443));
  }
 else {
    schemeRegistry.register(new Scheme("https",new EasySSLSocketFactory(),443));
  }
  ThreadSafeClientConnManager cm=new ThreadSafeClientConnManager(httpParams,schemeRegistry);
  httpClient=new DefaultHttpClient(cm,httpParams);
}
 

Example 84

From project DTE, under directory /src/cl/nic/dte/net/.

Source file: ConexionSii.java

  34 
vote

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia,String rutCompania,File archivoEnviarSII,String token,String urlEnvio,String hostEnvio) throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(urlEnvio);
  MultipartEntity reqEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  reqEntity.addPart("rutSender",new StringBody(rutEnvia.substring(0,rutEnvia.length() - 2)));
  reqEntity.addPart("dvSender",new StringBody(rutEnvia.substring(rutEnvia.length() - 1,rutEnvia.length())));
  reqEntity.addPart("rutCompany",new StringBody(rutCompania.substring(0,(rutCompania).length() - 2)));
  reqEntity.addPart("dvCompany",new StringBody(rutCompania.substring(rutCompania.length() - 1,rutCompania.length())));
  FileBody bin=new FileBody(archivoEnviarSII);
  reqEntity.addPart("archivo",bin);
  httppost.setEntity(reqEntity);
  BasicClientCookie cookie=new BasicClientCookie("TOKEN",token);
  cookie.setPath("/");
  cookie.setDomain(hostEnvio);
  cookie.setSecure(true);
  cookie.setVersion(1);
  CookieStore cookieStore=new BasicCookieStore();
  cookieStore.addCookie(cookie);
  httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2109);
  httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
  HttpContext localContext=new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
  httppost.addHeader(new BasicHeader("User-Agent",Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));
  HttpResponse response=httpclient.execute(httppost,localContext);
  HttpEntity resEntity=response.getEntity();
  RECEPCIONDTEDocument resp=null;
  HashMap<String,String> namespaces=new HashMap<String,String>();
  namespaces.put("","http://www.sii.cl/SiiDte");
  XmlOptions opts=new XmlOptions();
  opts.setLoadSubstituteNamespaces(namespaces);
  resp=RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity),opts);
  return resp;
}
 

Example 85

From project E12Planner, under directory /src/com/neoware/europlanner/.

Source file: ReadDataAsyncTask.java

  34 
vote

@Override protected Boolean doInBackground(String... params){
  try {
    HttpClient httpClient=new DefaultHttpClient();
    HttpParams httpParams=httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,30000);
    HttpConnectionParams.setSoTimeout(httpParams,30000);
    HttpGet get=new HttpGet(params[0]);
    mData=httpClient.execute(get,new BasicResponseHandler());
    return true;
  }
 catch (  ClientProtocolException ex) {
    mErrorMessage=ex.getMessage();
  }
catch (  IOException ex) {
    mErrorMessage=ex.getMessage();
  }
  return false;
}
 

Example 86

From project eoit, under directory /EOIT/src/fr/eoit/util/.

Source file: AndroidUrlDownloader.java

  34 
vote

@Override public InputStream urlToInputStream(String url) throws DownloadException {
  try {
    HttpClient httpclient=new DefaultHttpClient();
    HttpGet httpget=new HttpGet(url);
    httpget.addHeader("Accept-Encoding","gzip");
    HttpResponse response;
    response=httpclient.execute(httpget);
    Log.v(LOG_TAG,response.getStatusLine().toString());
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream instream=entity.getContent();
      Header contentEncoding=response.getFirstHeader("Content-Encoding");
      if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
        Log.v(LOG_TAG,"Accepting gzip for url : " + url);
        instream=new GZIPInputStream(instream);
      }
      return instream;
    }
  }
 catch (  IllegalStateException e) {
    throw new DownloadException(e);
  }
catch (  IOException e) {
    throw new DownloadException(e);
  }
  return null;
}
 

Example 87

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: AsyncHttpClient.java

  33 
vote

private void sendRequest(DefaultHttpClient client,HttpContext httpContext,HttpUriRequest uriRequest,String contentType,AsyncHttpResponseHandler responseHandler,Context context){
  if (contentType != null) {
    uriRequest.addHeader("Content-Type",contentType);
  }
  Future<?> request=threadPool.submit(new AsyncHttpRequest(client,httpContext,uriRequest,responseHandler));
  if (context != null) {
    List<WeakReference<Future<?>>> requestList=requestMap.get(context);
    if (requestList == null) {
      requestList=new LinkedList<WeakReference<Future<?>>>();
      requestMap.put(context,requestList);
    }
    requestList.add(new WeakReference<Future<?>>(request));
  }
}
 

Example 88

From project chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.

Source file: Chargify.java

  33 
vote

protected DefaultHttpClient createHttpClient(){
  if (beanFactory == null) {
    beanFactory=new XmlBeanFactory(new ClassPathResource("sense-context.xml"));
  }
  return (DefaultHttpClient)beanFactory.getBean("httpClient",DefaultHttpClient.class);
}
 

Example 89

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/factory/httpclient4/.

Source file: ApacheHttpClient4Factory.java

  33 
vote

private <T>void contributeCookies(final DefaultHttpClient httpClient,final HttpClientRequest<T> httpClientRequest){
  final List<Cookie> cookies=httpClientRequest.getCookies();
  if (CollectionUtils.isNotEmpty(cookies)) {
    final CookieStore cookieStore=new BasicCookieStore();
    for (    final Cookie cookie : cookies) {
      final BasicClientCookie httpCookie=new BasicClientCookie(cookie.getName(),cookie.getValue());
      final int maxAge=cookie.getMaxAge();
      if (maxAge > 0) {
        final Date expire=new Date(System.currentTimeMillis() + maxAge * 1000L);
        httpCookie.setExpiryDate(expire);
        httpCookie.setAttribute(ClientCookie.MAX_AGE_ATTR,Integer.toString(maxAge));
      }
      httpCookie.setVersion(1);
      httpCookie.setPath(cookie.getPath());
      httpCookie.setDomain(cookie.getDomain());
      httpCookie.setSecure(cookie.getSecure());
      LOG.debug("Adding cookie to the request: '%s'",httpCookie);
      cookieStore.addCookie(httpCookie);
    }
    httpClient.setCookieStore(cookieStore);
  }
 else {
    LOG.debug("No cookies found.");
    httpClient.setCookieStore(null);
  }
}
 

Example 90

From project emite, under directory /src/test/java/com/calclab/emite/xtesting/services/.

Source file: HttpConnector.java

  33 
vote

private Runnable createSendAction(final String httpBase,final String xml,final ConnectorCallback callback){
  return new Runnable(){
    @Override public void run(){
      final String id=HttpConnectorID.getNext();
      debug("Connector [{0}] send: {1}",id,xml);
      final HttpClient client=new DefaultHttpClient();
      int status=0;
      String responseString=null;
      final HttpPost post=new HttpPost(httpBase);
      try {
        post.setEntity(new StringEntity(xml,"utf-8"));
        System.out.println("SENDING: " + xml);
        final HttpResponse response=client.execute(post);
        responseString=EntityUtils.toString(response.getEntity());
      }
 catch (      final Exception e) {
        callback.onResponseError(xml,e);
        e.printStackTrace();
      }
      try {
        post.setEntity(new StringEntity(xml,"text/xml"));
        System.out.println("SENDING: " + xml);
        HttpResponse response=client.execute(post);
        responseString=EntityUtils.toString(response.getEntity());
        status=response.getStatusLine().getStatusCode();
      }
 catch (      final Exception e) {
        callback.onResponseError(xml,e);
        e.printStackTrace();
      }
      receiveService.execute(createResponseAction(xml,callback,id,status,responseString));
    }
  }
;
}