android.net.http.AndroidHttpClient Java Examples

The following examples show how to use android.net.http.AndroidHttpClient. 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 6 votes vote down vote up
public File downloadByUrl(String urlString) {
	AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null);
	HttpGet get = new HttpGet(urlString);
	File file = null;
	try {
		HttpResponse response = httpClient.execute(get);
		if (response.getStatusLine().getStatusCode() == STATUS_OK) {
			HttpEntity entity = response.getEntity();
			file = mFileHandler.createEmptyFileToDownloadDirectory(MD5Encoder.encoding(urlString));
			entity.writeTo(new FileOutputStream(file));
		} else if (response.getStatusLine().getStatusCode() == 404) {
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} finally {
		httpClient.close();
		httpClient = null;
	}
	return file;
}
 
Example #3
Source File: Hosaka.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, HosakaColumn> handleResponse (final HttpResponse response) throws IOException {
	checkReponseCode(response.getStatusLine());
	try {
		final String str = IoHelper.toString(AndroidHttpClient.getUngzippedContent(response.getEntity()));
		final JSONObject o = (JSONObject) new JSONTokener(str).nextValue();
		final Map<String, HosakaColumn> ret = new HashMap<String, HosakaColumn>();
		final Iterator<String> keys = o.keys();
		while (keys.hasNext()) {
			final String key = keys.next();
			ret.put(key, HosakaColumn.parseJson(o.getJSONObject(key)));
		}
		return ret;
	}
	catch (final JSONException e) {
		throw new IOException(e); // FIXME
	}
}
 
Example #4
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
public TweetList getFeed (final SuccessWhaleFeed feed, final String sinceId, final Collection<Meta> extraMetas) throws SuccessWhaleException {
		return authenticated(new SwCall<TweetList>() {
			private String url;

			@Override
			public TweetList invoke (final HttpClient client) throws IOException {
				this.url = makeAuthedUrl(API_FEED, "&sources=", URLEncoder.encode(feed.getSources(), "UTF-8"));

				// FIXME disabling this until SW finds a way to accept it on mixed feeds [issue 89].
//				if (sinceId != null) this.url += "&since_id=" + sinceId;

				final HttpGet req = new HttpGet(this.url);
				AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
				return client.execute(req, new FeedHandler(getAccount(), extraMetas));
			}

			@Override
			public String describeFailure (final Exception e) {
				return "Failed to fetch feed '" + feed + "' from '" + this.url + "': " + e.toString();
			}
		});
	}
 
Example #5
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> handleResponse (final HttpResponse response) throws ClientProtocolException, IOException {
	checkReponseCode(response);
	final String raw = IoHelper.toString(AndroidHttpClient.getUngzippedContent(response.getEntity()));
	try {
		final JSONArray arr = ((JSONObject) new JSONTokener(raw).nextValue()).getJSONArray("bannedphrases");
		final List<String> ret = new ArrayList<String>();
		for (int i = 0; i < arr.length(); i++) {
			ret.add(arr.getString(i));
		}
		return ret;
	}
	catch (final JSONException e) {
		throw new IOException("Failed to parse response: " + e.toString(), e);
	}
}
 
Example #6
Source File: DownloadThread.java    From mobile-manager-tool with MIT License 6 votes vote down vote up
/**
    * Fully execute a single download request - setup and send the request,
    * handle the response, and transfer the data to the destination file.
    */
   private void executeDownload(State state, AndroidHttpClient client,
    HttpGet request) throws StopRequest, RetryDownload {
InnerState innerState = new InnerState();
byte data[] = new byte[Constants.BUFFER_SIZE];

setupDestinationFile(state, innerState);
addRequestHeaders(innerState, request);

// check just before sending the request to avoid using an invalid
// connection at all
checkConnectivity(state);

HttpResponse response = sendRequest(state, client, request);
handleExceptionalStatus(state, innerState, response);

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

processResponseHeaders(state, innerState, response);
InputStream entityStream = openResponseEntity(state, response);
transferData(state, innerState, data, entityStream);
   }
 
Example #7
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 6 votes vote down vote up
public TweetList getThread (final String serviceType, final String serviceSid, final String forSid) throws SuccessWhaleException {
	return authenticated(new SwCall<TweetList>() {
		@Override
		public TweetList invoke (final HttpClient client) throws IOException {
			final String url = makeAuthedUrl(API_THREAD, "&service=", serviceType, "&uid=" + serviceSid, "&postid=", forSid);
			final HttpGet req = new HttpGet(url);
			AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
			final TweetList thread = client.execute(req, new FeedHandler(getAccount(), null));
			return removeItem(thread, forSid);
		}

		@Override
		public String describeFailure (final Exception e) {
			return "Failed to fetch thread for sid='" + forSid + "': " + e.toString();
		}
	});
}
 
Example #8
Source File: HttpClientWrapper.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
public HttpClientWrapper(AppIdentification appIdentification,
		NetworkMetricsCollectorService metricsCollector,
           ApigeeActiveSettings activeSettings)
{
	
	HttpClient delegateClient = AndroidHttpClient.newInstance(appIdentification.getApplicationId());
	initialize(appIdentification, metricsCollector, activeSettings,
			delegateClient);
}
 
Example #9
Source File: Volley.java    From okulus 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 android.content.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 CrossBow 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: HttpStackSelector.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
public static HttpStack createStack() {
    if(hasOkHttp()) {
        OkHttpClient okHttpClient = new OkHttpClient();
        VolleyLog.d("OkHttp found, using okhttp for http stack");
        return new OkHttpStack(okHttpClient);
    }
    else if (useHttpClient()){
        VolleyLog.d("Android version is older than Gingerbread (API 9), using HttpClient");
        return new HttpClientStack(AndroidHttpClient.newInstance(USER_AGENT));
    }
    else {
        VolleyLog.d("Using Default HttpUrlConnection");
        return new HurlStack();
    }
}
 
Example #12
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 #13
Source File: Volley.java    From barterli_android 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(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 DiskBasedCache(cacheDir), network, new BasicUrlRewriter());
    queue.start();

    return queue;
}
 
Example #14
Source File: Volley.java    From android_tv_metro with Apache License 2.0 5 votes vote down vote up
public static RequestQueue newRequestQueue(Context context, HttpStack stack, String dir, int cacheSize) {
    File cacheDir = new File(context.getCacheDir(), 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, cacheSize), network);
    queue.start();

    return queue;
}
 
Example #15
Source File: Volley.java    From android_tv_metro 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 #16
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 #17
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 #18
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
public SuccessWhaleColumns getColumns () throws SuccessWhaleException {
	return authenticated(new SwCall<SuccessWhaleColumns>() {
		@Override
		public SuccessWhaleColumns invoke (final HttpClient client) throws IOException {
			final HttpGet req = new HttpGet(makeAuthedUrl(API_COLUMNS));
			AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
			return client.execute(req, new ColumnsHandler(getAccount()));
		}

		@Override
		public String describeFailure (final Exception e) {
			return "Failed to fetch columns: " + e.toString();
		}
	});
}
 
Example #19
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
public SuccessWhaleSources getSources () throws SuccessWhaleException {
	return authenticated(new SwCall<SuccessWhaleSources>() {
		@Override
		public SuccessWhaleSources invoke (final HttpClient client) throws IOException {
			final HttpGet req = new HttpGet(makeAuthedUrl(API_SOURCES));
			AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
			return client.execute(req, SourcesHandler.INSTANCE);
		}

		@Override
		public String describeFailure (final Exception e) {
			return "Failed to fetch sources: " + e.toString();
		}
	});
}
 
Example #20
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
public List<String> getBannedPhrases () throws SuccessWhaleException {
	return authenticated(new SwCall<List<String>>() {
		@Override
		public List<String> invoke (final HttpClient client) throws IOException {
			final HttpGet req = new HttpGet(makeAuthedUrl(API_BANNED_PHRASES));
			AndroidHttpClient.modifyRequestToAcceptGzipResponse(req);
			return client.execute(req, BannedPhrasesHandler.INSTANCE);
		}

		@Override
		public String describeFailure (final Exception e) {
			return "Failed to fetch banned phrases: " + e.toString();
		}
	});
}
 
Example #21
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
public SuccessWhaleColumns handleResponse (final HttpResponse response) throws IOException {
	checkReponseCode(response);
	try {
		return new ColumnsXml(this.account, AndroidHttpClient.getUngzippedContent(response.getEntity())).getColumns();
	}
	catch (final SAXException e) {
		throw new IOException("Failed to parse response: " + e.toString(), e);
	}
}
 
Example #22
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
public SuccessWhaleSources handleResponse (final HttpResponse response) throws IOException {
	checkReponseCode(response);
	try {
		return new SourcesXml(AndroidHttpClient.getUngzippedContent(response.getEntity())).getSources();
	}
	catch (final SAXException e) {
		throw new IOException("Failed to parse response: " + e.toString(), e);
	}
}
 
Example #23
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
public TweetList handleResponse (final HttpResponse response) throws IOException {
	checkReponseCode(response);
	try {
		final HttpEntity entity = response.getEntity();
		LOG.d("Feed content encoding: '%s', headers: %s.", entity.getContentEncoding(), Arrays.asList(response.getAllHeaders()));
		return new SuccessWhaleFeedXml(this.account, AndroidHttpClient.getUngzippedContent(entity), this.extraMetas).getTweets();
	}
	catch (final SAXException e) {
		throw new IOException("Failed to parse response: " + e.toString(), e);
	}
}
 
Example #24
Source File: Hosaka.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
public Map<String, HosakaColumn> sendColumns (final Map<String, HosakaColumn> columns) throws IOException, JSONException {
	final HttpPost post = new HttpPost(BASE_URL + API_COLUMNS);
	AndroidHttpClient.modifyRequestToAcceptGzipResponse(post);
	addAuth(post);

	final JSONObject columnsJson = new JSONObject();
	for (final Entry<String, HosakaColumn> e : columns.entrySet()) {
		columnsJson.put(e.getKey(), e.getValue().toJson());
	}
	post.setEntity(new StringEntity(columnsJson.toString(), "UTF-8"));

	return getHttpClient().execute(post, new HosakaColumnsHandler());
}
 
Example #25
Source File: AndroidChannel.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
void setHttpClientForTest(HttpClient client) {
  if (this.httpClient instanceof AndroidHttpClient) {
    // Release the previous client if any.
    ((AndroidHttpClient) this.httpClient).close();
  }
  super.setHttpClientForTest(client);
}
 
Example #26
Source File: AndroidChannel.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
void setHttpClientForTest(HttpClient client) {
  if (this.httpClient instanceof AndroidHttpClient) {
    // Release the previous client if any.
    ((AndroidHttpClient) this.httpClient).close();
  }
  super.setHttpClientForTest(client);
}
 
Example #27
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 #28
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 #29
Source File: Volley.java    From SimplifyReader 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 android.content.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 #30
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;
}