Java Code Examples for android.net.http.AndroidHttpClient#newInstance()

The following examples show how to use android.net.http.AndroidHttpClient#newInstance() . 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: FileDownLoad.java    From wallpaper with GNU General Public License v2.0 6 votes vote down vote up
public boolean downloadByUrl(String urlString, String fileName) {
	boolean downloadSucceed = false;
	AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);
	// HttpPost post = new HttpPost(urlString);
	HttpGet get = new HttpGet(urlString);
	HttpResponse response = null;
	try {
		response = httpClient.execute(get);
		if (response.getStatusLine().getStatusCode() == STATUS_OK) {
			HttpEntity entity = response.getEntity();
			File file = mFileHandler.createEmptyFileToDownloadDirectory(fileName);
			entity.writeTo(new FileOutputStream(file));
			downloadSucceed = true;
		} else {
		}

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		httpClient.close();
	}
	return downloadSucceed;
}
 
Example 2
Source File: FileDownLoad.java    From wallpaper with GNU General Public License v2.0 5 votes vote down vote up
public boolean downloadByUrlByGzip(String urlString, String fileName) {
	boolean downloadSucceed = false;

	AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);
	httpClient.getParams().setParameter("Accept-Encoding", "gzip");
	HttpPost post = new HttpPost(urlString);
	HttpResponse response = null;

	try {
		response = httpClient.execute(post);
		if (response.getStatusLine().getStatusCode() == STATUS_OK) {
			HttpEntity entity = response.getEntity();
			File file = mFileHandler.createEmptyFileToDownloadDirectory(fileName);

			InputStream inputStream = AndroidHttpClient.getUngzippedContent(entity);
			downloadSucceed = StreamUtils.writeStreamToFile(inputStream, file);
		} else {
			System.out.println("---");
		}

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		httpClient.close();
	}
	return downloadSucceed;
}
 
Example 3
Source File: Volley.java    From FeedListViewDemo with MIT License 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 4
Source File: Volley.java    From volley with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack A {@link BaseHttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, BaseHttpStack stack) {
    BasicNetwork network;
    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            network = new BasicNetwork(new HurlStack());
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            // At some point in the future we'll move our minSdkVersion past Froyo and can
            // delete this fallback (along with all Apache HTTP code).
            String userAgent = "volley/0";
            try {
                String packageName = context.getPackageName();
                PackageInfo info =
                        context.getPackageManager().getPackageInfo(packageName, /* flags= */ 0);
                userAgent = packageName + "/" + info.versionCode;
            } catch (NameNotFoundException e) {
            }

            network =
                    new BasicNetwork(
                            new HttpClientStack(AndroidHttpClient.newInstance(userAgent)));
        }
    } else {
        network = new BasicNetwork(stack);
    }

    return newRequestQueue(context, network);
}
 
Example 5
Source File: Volley.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 6
Source File: Volley.java    From device-database with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 7
Source File: Volley.java    From volley with Apache License 2.0 5 votes vote down vote up
/**
 * 不带缓存的requestQueue
 * newNoCacheRequestQueue
 * @param context
 * @param stack
 * @return
 * @since 3.5
 */
public static RequestQueue newNoCacheRequestQueue(Context context) {
    String userAgent = null;
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    HttpStack stack = null;
    if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack(userAgent);
    } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See:
        // http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new NoCache(), network);
    queue.start();

    return queue;
}
 
Example 8
Source File: Volley.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 9
Source File: Volley.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 10
Source File: Volley.java    From android-common-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 11
Source File: ImageLoader.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
private static RequestQueue newRequestQueue(Context context) {

        // On HC+ use HurlStack which is based on HttpURLConnection. Otherwise fall back on
        // AndroidHttpClient (based on Apache DefaultHttpClient) which should no longer be used
        // on newer platform versions where HttpURLConnection is simply better.
        Network network = new BasicNetwork(Utils.hasHoneycomb() ? new HurlStack() : new HttpClientStack(AndroidHttpClient.newInstance(Utils.getUserAgent(context))));

        Cache cache = new DiskBasedCache(getDiskCacheDir(context, CACHE_DIR), DEFAULT_DISK_USAGE_BYTES);
        RequestQueue queue = new RequestQueue(cache, network);
        queue.start();
        return queue;
    }
 
Example 12
Source File: Volley.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 13
Source File: Volley.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack   An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */
public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();

    return queue;
}
 
Example 14
Source File: LauncherActivity.java    From Android-Plugin-Framework with MIT License 4 votes vote down vote up
private void testUseLibray() {
	AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance("test/test", getApplicationContext());
	ClassLoader classloader = androidHttpClient.getClass().getClassLoader();
	android.util.Log.e("LauncherActivity", "testUseLibray, classloader=" + classloader);
}
 
Example 15
Source File: ExampleSocialActivity.java    From android-profile with Apache License 2.0 4 votes vote down vote up
private Bitmap downloadBitmapWithClient(String url) {
    final AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");
    HttpClientParams.setRedirecting(httpClient.getParams(), true);
    final HttpGet request = new HttpGet(url);

    try {
        HttpResponse response = httpClient.execute(request);
        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            Header[] headers = response.getHeaders("Location");

            if (headers != null && headers.length != 0) {
                String newUrl = headers[headers.length - 1].getValue();
                // call again with new URL
                return downloadBitmap(newUrl);
            } else {
                return null;
            }
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();

                // do your work here
                return BitmapFactory.decodeStream(inputStream);
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (Exception e) {
        request.abort();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }

    return null;
}
 
Example 16
Source File: AndroidChannel.java    From android-chromium with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * Returns the default HTTP client to use for requests from the channel based upon its execution
 * context.  The format of the User-Agent string is "<application-pkg>(<android-release>)".
 */
static AndroidHttpClient getDefaultHttpClient(Context context) {
  return AndroidHttpClient.newInstance(
     context.getApplicationInfo().className + "(" + Build.VERSION.RELEASE + ")");
}
 
Example 17
Source File: AndroidApacheClient.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
public AndroidApacheClient() {
    super(AndroidHttpClient.newInstance("Retrofit"));
}
 
Example 18
Source File: MainActivity.java    From Android-Plugin-Framework with MIT License 4 votes vote down vote up
private void testUseLibray() {
    AndroidHttpClient androidHttpClient = AndroidHttpClient.newInstance("test/test", getApplicationContext());
    ClassLoader classloader = androidHttpClient.getClass().getClassLoader();
    Log.e("MainActivity", "testUseLibray, classloader=" + classloader);
}
 
Example 19
Source File: Volley.java    From SaveVolley with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.
 *
 * @param context A {@link Context} to use for creating the cache dir.
 * @param stack An {@link HttpStack} to use for the network, or null for default.
 * @return A started {@link RequestQueue} instance.
 */

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    // 创建 缓存文件夹
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        // 重新编辑 userAgent
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }

    // 如果已经提供了 HttpStack
    if (stack == null) {
        /*
         * API 9 以上:Android 2.3 以上
         * 网络请求用的是 HttpUrlConnection
         */
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            /*
             * API 9 以上:Android 2.3 以上
             * 网络请求用的是 Apache HttpClient
             * 需要 设置 Apache HttpClient userAgent
             */
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    /*
     * 创建一个 BasicNetwork
     * 提供给 RequestQueue 使用
     */
    Network network = new BasicNetwork(stack);

    /*
     * 创建一个 RequestQueue
     * 需要提供的:
     * 1. cacheDir,去创建一个 DiskBasedCache
     * 2. network,BasicNetwork
     */
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    // 启动 请求队列
    queue.start();

    return queue;
}
 
Example 20
Source File: DownloadThread.java    From mobile-manager-tool with MIT License 4 votes vote down vote up
/**
    * Executes the download in a separate thread
    */
   public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

State state = new State(mInfo);
AndroidHttpClient client = null;
PowerManager.WakeLock wakeLock = null;
int finalStatus = Downloads.STATUS_UNKNOWN_ERROR;

try {
    PowerManager pm = (PowerManager) mContext
	    .getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
	    Constants.TAG);
    wakeLock.acquire();

    if (Constants.LOGV) {
	Log.v(Constants.TAG, "initiating download for " + mInfo.mUri);
    }

    client = AndroidHttpClient.newInstance(userAgent(), mContext);

    boolean finished = false;
    while (!finished) {
	Log.i(Constants.TAG, "Initiating request for download "
		+ mInfo.mId);
	HttpGet request = new HttpGet(state.mRequestUri);
	try {
	    executeDownload(state, client, request);
	    finished = true;
	} catch (RetryDownload exc) {
	    // fall through
	} finally {
	    request.abort();
	    request = null;
	}
    }

    if (Constants.LOGV) {
	Log.v(Constants.TAG, "download completed for " + mInfo.mUri);
    }
    finalizeDestinationFile(state);
    finalStatus = Downloads.STATUS_SUCCESS;
} catch (StopRequest error) {
    // remove the cause before printing, in case it contains PII
    Log.w(Constants.TAG, "Aborting request for download " + mInfo.mId
	    + ": " + error.getMessage());
    finalStatus = error.mFinalStatus;
    // fall through to finally block
} catch (Throwable ex) { // sometimes the socket code throws unchecked
			 // exceptions
    Log.w(Constants.TAG, "Exception for id " + mInfo.mId + ": " + ex);
    finalStatus = Downloads.STATUS_UNKNOWN_ERROR;
    // falls through to the code that reports an error
} finally {
    if (wakeLock != null) {
	wakeLock.release();
	wakeLock = null;
    }
    if (client != null) {
	client.close();
	client = null;
    }
    cleanupDestination(state, finalStatus);
    notifyDownloadCompleted(finalStatus, state.mCountRetry,
	    state.mRetryAfter, state.mGotData, state.mFilename,
	    state.mNewUri, state.mMimeType);
    mInfo.mHasActiveThread = false;
}
   }