Java 类android.net.http.AndroidHttpClient 实例源码

项目:airgram    文件:Volley.java   
/**
 * 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;
}
项目:Leanplum-Android-SDK    文件:SocketIOClient.java   
private static String downloadUriAsString(final HttpUriRequest req)
    throws IOException {
  AndroidHttpClient client = AndroidHttpClient.newInstance(userAgentString());
  try {
    HttpResponse res = client.execute(req);
    return readToEnd(res.getEntity().getContent());
  } finally {
    client.close();
  }
}
项目:darksms    文件:HttpUtils.java   
private static AndroidHttpClient createHttpClient(Context context) {
    String userAgent = MmsConfig.getUserAgent();
    AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent, context);
    HttpParams params = client.getParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    // set the socket timeout
    int soTimeout = MmsConfig.getHttpSocketTimeout();

    if (DEBUG) {
        Log.d(TAG, "[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, "
                + ", UA=" + userAgent);
    }
    HttpConnectionParams.setSoTimeout(params, soTimeout);
    return client;
}
项目:mobile-manager-tool    文件:DownloadThread.java   
/**
    * 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);
   }
项目:android.java    文件:Volley.java   
private static HttpStack getDefaultStack(Context context){
    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();

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

    if (Build.VERSION.SDK_INT >= 9) {
       return new HurlStack();
    } else {
        // Prior to Gingerbread, HttpUrlConnection was unreliable.
        // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        return new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
    }       
}
项目:FHWS-MobileApplikationen    文件:MainActivity.java   
@Override
protected String doInBackground(String... url) {

    AndroidHttpClient httpClient = AndroidHttpClient.newInstance("test");
    HttpGet get = new HttpGet("http://backend.applab.fhws.de:8080/fhws/simple");

    try
    {
        HttpResponse response = httpClient.execute(get);
        InputStream is = response.getEntity().getContent();

        return IOUtils.toString(is);
    }
    catch( Exception e )
    {
        e.printStackTrace();
    }

    return "Error";
}
项目:FHWS-MobileApplikationen    文件:DemoAppWidget.java   
@Override
protected String doInBackground( Void... params )
{
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance( "" );
    HttpGet get = new HttpGet( URL );

    try
    {
        HttpResponse response = httpClient.execute( get );
        HttpEntity entity = response.getEntity( );
        InputStreamReader reader = new InputStreamReader( entity.getContent( ) );
        BufferedReader bufReader = new BufferedReader( reader );

        String status = bufReader.readLine( );
        entity.consumeContent( );

        return status;
    }
    catch ( Exception e )
    {
        Log.e( "WIDGET", e.getMessage( ) );
    }

    return "No status received";
}
项目:Fabric-Example-App-Android    文件:VastXmlManagerAggregator.java   
@Override
protected VastVideoConfiguration doInBackground(@Nullable String... strings) {
    AndroidHttpClient httpClient = null;
    try {
        httpClient = HttpClient.getHttpClient();
        if (strings != null && strings.length > 0) {
            String vastXml = strings[0];
            if (vastXml == null) {
                return null;
            }
            return evaluateVastXmlManager(vastXml, httpClient, new ArrayList<VastTracker>());
        }
    } catch (Exception e) {
        MoPubLog.d("Failed to parse VAST XML", e);
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }

    return null;
}
项目:Fabric-Example-App-Android    文件:VastXmlManagerAggregator.java   
/**
 * Retrieves the Wrapper's redirect uri and follows it to return the next VAST xml String.
 *
 * @param vastWrapperXmlManager used to get the redirect uri
 * @param androidHttpClient     the http client
 * @param wrapperErrorTrackers  Error trackers to hit if something goes wrong
 * @return the next VAST xml String or {@code null} if it could not be resolved
 */
@Nullable
private String evaluateWrapperRedirect(@NonNull VastWrapperXmlManager vastWrapperXmlManager,
        @NonNull AndroidHttpClient androidHttpClient,
        @NonNull List<VastTracker> wrapperErrorTrackers) {
    String vastAdTagUri = vastWrapperXmlManager.getVastAdTagURI();
    if (vastAdTagUri == null) {
        return null;
    }

    String vastRedirectXml = null;
    try {
        vastRedirectXml = followVastRedirect(androidHttpClient, vastAdTagUri);
    } catch (Exception e) {
        MoPubLog.d("Failed to follow VAST redirect", e);
        if (!wrapperErrorTrackers.isEmpty()) {
            makeVastTrackingHttpRequest(wrapperErrorTrackers, VastErrorCode.WRAPPER_TIMEOUT,
                            null, null, mContext);
        }
    }

    return vastRedirectXml;
}
项目:Fabric-Example-App-Android    文件:VastXmlManagerAggregator.java   
@Nullable
private String followVastRedirect(@NonNull final AndroidHttpClient httpClient,
        @NonNull final String redirectUrl) throws Exception {
    Preconditions.checkNotNull(httpClient);
    Preconditions.checkNotNull(redirectUrl);

    if (mTimesFollowedVastRedirect < MAX_TIMES_TO_FOLLOW_VAST_REDIRECT) {
        mTimesFollowedVastRedirect++;

        final HttpGet httpget = HttpClient.initializeHttpGet(redirectUrl);
        final HttpResponse response = httpClient.execute(httpget);
        final HttpEntity entity = response.getEntity();
        return (entity != null) ? Strings.fromStream(entity.getContent()) : null;
    }
    return null;
}
项目:Fabric-Example-App-Android    文件:DownloadTask.java   
@Override
protected DownloadResponse doInBackground(final HttpUriRequest... httpUriRequests) {
    if (httpUriRequests == null || httpUriRequests.length == 0 || httpUriRequests[0] == null) {
        MoPubLog.d("Download task tried to execute null or empty url");
        return null;
    }

    final HttpUriRequest httpUriRequest = httpUriRequests[0];
    mUrl = httpUriRequest.getURI().toString();

    AndroidHttpClient httpClient = null;
    try {
        httpClient = HttpClient.getHttpClient();
        final HttpResponse httpResponse = httpClient.execute(httpUriRequest);
        return new DownloadResponse(httpResponse);
    } catch (Exception e) {
        MoPubLog.d("Download task threw an internal exception", e);
        return null;
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}
项目:BitcoinCardTerminal    文件:WebUtil.java   
public static SimpleWebResponse SimpleHttpGet(AndroidHttpClient client, String url, String contentType, String callerDebugName) throws IOException{
    String netResult = "", line;

    HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("accept", contentType);

    HttpResponse response = client.execute(getRequest);


    if (response.getStatusLine().getStatusCode() != 200) {
        HttpResponseLog(response, callerDebugName);
        return new SimpleWebResponse(null, false);
    }else{
        BufferedReader br = new BufferedReader(
                         new InputStreamReader((response.getEntity().getContent())));

        while ((line = br.readLine()) != null) {
            netResult = netResult + line;
        }
    }

    return new SimpleWebResponse(netResult, true);
}
项目:BitcoinCardTerminal    文件:WebUtil.java   
public static SimpleWebResponse SimpleHttpPost(AndroidHttpClient client, String url, String body, String contentType, String callerDebugName) throws IOException {
    String netResult = "", line;

    HttpPost postRequest = new HttpPost(url);
    postRequest.addHeader("accept", contentType);
    postRequest.setEntity(new StringEntity(body, "UTF8"));

    HttpResponse response = client.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        HttpResponseLog(response, callerDebugName);
        return new SimpleWebResponse(null, false);
    }else{
        BufferedReader br = new BufferedReader(
                         new InputStreamReader((response.getEntity().getContent())));

        while ((line = br.readLine()) != null) {
            netResult = netResult + line;
        }
    }

    return new SimpleWebResponse(netResult, true);
}
项目:BitcoinCardTerminal    文件:StratumServerManager.java   
private void AddServersFromOnlineSource(){
    //Get updated servers list from BlochsTech.com/StratumServers.json
    try{
        AndroidHttpClient client = AndroidHttpClient.newInstance("BOBC-0 Terminal/0.0/Android");
        SimpleWebResponse resp = WebUtil.SimpleHttpGet(client, "http://blochstech.com/content/StratumServers.txt", "text/plain", "StratumServerManager_GetBlochsTechServerList");
        if(resp.IsConnected && resp.Response != null){
            JSONObject json = new JSONObject(resp.Response);
            JSONArray jsonServers = json.getJSONArray("Servers");
            String url;
            for(int i = 0; i < jsonServers.length(); i++){
                url = jsonServers.getString(i);
                if(!ContainsServer(url))
                    servers.add(new StratumServer(url));
            }
        }
    }catch(Exception ex){
        if(Tags.DEBUG)
            Log.e(Tags.APP_TAG, "Failed to get StratumServers from online source. Ex: " + ex.toString());
    }
}
项目:Wardrobe_app    文件:ImageLoader.java   
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(
                UIUtils.hasHoneycomb() ?
                        new HurlStack() :
                        new HttpClientStack(AndroidHttpClient.newInstance(
                                NetUtils.getUserAgent(context))));

        Cache cache = new DiskBasedCache(getDiskCacheDir(context, CACHE_DIR));
        RequestQueue queue = new RequestQueue(cache, network);
        queue.start();
        return queue;
    }
项目:rothar-android-app    文件:CommunicationService.java   
@Override
protected HttpResponse doInBackground(String... params) {           
    String link = params[0];
    String payload = params[1];
    AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    HttpPost request = new HttpPost(link);
    HttpResponse response = null;
    request.setHeader( "Content-Type", "application/json" );
    try {
        StringEntity se = new StringEntity(payload);
     se.setContentEncoding("UTF-8");
     se.setContentType("application/json");         
     request.setEntity(se);             
     response = client.execute(request);
    } catch (IOException e) {
        log(e.getMessage());
        e.printStackTrace();
    } finally {
        client.close();
    }
    return response;
}
项目:sms_DualCard    文件:HttpUtils.java   
private static AndroidHttpClient createHttpClient(Context context) {
    String userAgent = MmsConfig.getUserAgent();
    AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent, context);
    HttpParams params = client.getParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    // set the socket timeout
    int soTimeout = MmsConfig.getHttpSocketTimeout();

    if (Log.isLoggable(LogTag.TRANSACTION, Log.DEBUG)) {
        Log.d(TAG, "[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, "
                + ", UA=" + userAgent);
    }
    HttpConnectionParams.setSoTimeout(params, soTimeout);
    return client;
}
项目:DragonGoApp    文件:AndroidServerConnection.java   
void initHttp() {
    if (httpclientdirect==null) {
        httpclientdirect = AndroidHttpClient.newInstance(null);
        httpctxt = new BasicHttpContext();
        httpctxt.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
        // login
        try {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("userid", u));
            formparams.add(new BasicNameValuePair("passwd", p));
            formparams.add(new BasicNameValuePair("login", "Log+In"));
            UrlEncodedFormEntity entity;
            entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            HttpPost httppost = new HttpPost(getUrl()+"login.php");
            httppost.setEntity(entity);
            directConnectExecute(httppost,null);
            GoJsActivity.main.updateTraffic();
        } catch (Exception e) {
            e.printStackTrace();
            GoJsActivity.main.updateTraffic();
        }
    }
}
项目:mythling    文件:MediaStreamProxy.java   
private HttpResponse download() throws IOException {

        httpClient = AndroidHttpClient.newInstance("Android");
        // httpClient.getParams().setParameter(ClientPNames.VIRTUAL_HOST, new HttpHost("127.0.0.1"));

        URL netUrl = proxyInfo.netUrl;
        HttpHost host = new HttpHost(netUrl.getHost(), netUrl.getPort(), netUrl.getProtocol());

        HttpRequestBase request = new HttpGet(netUrl.toString());
        HttpResponse response = null;
        Log.d(TAG, "Proxy starting download");
        if (authType == AuthType.Digest) {
            HttpContext context = HttpHelper.getDigestAuthContext(netUrl.getHost(), netUrl.getPort(), proxyInfo.user, proxyInfo.password);
            response = httpClient.execute(host, request, context);
        }
        else if (authType == AuthType.Basic) {
            String credentials = Base64.encodeToString((proxyInfo.user + ":" + proxyInfo.password).getBytes(), Base64.DEFAULT);
            request.setHeader("Authorization", "Basic " + credentials);
            response = httpClient.execute(host, request);
        }
        else {
            response = httpClient.execute(host, request);
        }
        Log.d(TAG, "Proxy response downloaded");
        return response;
    }
项目:StockAnalyze    文件:DownloadService.java   
/**
     * initialize http client
     */
    public DownloadService() {
//      HttpParams params = new BasicHttpParams();
//      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
//      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
//      HttpProtocolParams.setUseExpectContinue(params, false);
//      ConnManagerParams.setMaxTotalConnections(params, 10);
//      HttpConnectionParams.setConnectionTimeout(params, 10 * 1000);
//      HttpConnectionParams.setSoTimeout(params, 10 * 1000);
//
//      SchemeRegistry schReg = new SchemeRegistry();
//      schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
//      schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        httpClient = AndroidHttpClient.newInstance("stockanalyze,gzip");
        HttpClientParams.setRedirecting(httpClient.getParams(), true);
    }
项目:Onosendai    文件:SuccessWhale.java   
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();
            }
        });
    }
项目:Onosendai    文件:SuccessWhale.java   
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();
        }
    });
}
项目:Onosendai    文件:SuccessWhale.java   
@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);
    }
}
项目:Onosendai    文件:Hosaka.java   
@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
    }
}
项目:otrta    文件:ServiceData.java   
public static String HttpGetAnswer(String url) throws ClientProtocolException, IOException, JSONException, HttpException{
    AndroidHttpClient client = AndroidHttpClient.newInstance(null);
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 7500);
    client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 7500);
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = client.execute(httpGet);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        String resp = EntityUtils.toString(response.getEntity());
        client.close();
        return resp;
    } else {
        try {
            client.close();
        }catch (Exception ex){}
        throw new HttpException("STATUSCODE!=200");
    }
}
项目:otrta    文件:ServiceData.java   
public static String HttpPostAnswer(String url, JSONObject jobj) throws ClientProtocolException, IOException, JSONException, HttpException{
    AndroidHttpClient client = AndroidHttpClient.newInstance(null);
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 7500);
    client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 7500);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(jobj.toString()));
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpResponse response = client.execute(httpPost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        String resp = EntityUtils.toString(response.getEntity());
        client.close();
        return resp;
    } else {
        try {
            client.close();
        }catch (Exception ex){}
        throw new HttpException("STATUSCODE!=200");
    }
}
项目:otrta    文件:ServiceData.java   
public static JSONObject HttpPostAnswerJsonObject(String url, JSONObject obj) throws ClientProtocolException, IOException, JSONException, HttpException{
    AndroidHttpClient client = AndroidHttpClient.newInstance(null);
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 60000);
    client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 60000);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(obj.toString()));
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpResponse response = client.execute(httpPost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        String raw = EntityUtils.toString(response.getEntity());
        JSONObject jobj = new JSONObject(raw);
        client.close();
        return jobj;
    } else {
        try {
            client.close();
        }catch (Exception ex){}
        throw new HttpException("STATUSCODE!=200");
    }
}
项目:otrta    文件:ServiceData.java   
public static JSONArray HttpPostAnswerJsonArray(String url, JSONObject obj) throws ClientProtocolException, IOException, JSONException, HttpException{
    AndroidHttpClient client = AndroidHttpClient.newInstance(null);
    client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
    client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 10000);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(obj.toString()));
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpResponse response = client.execute(httpPost);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
        String raw = EntityUtils.toString(response.getEntity());
        JSONArray jarr = new JSONArray(raw);
        client.close();
        return jarr;
    } else {
        try {
            client.close();
        }catch (Exception ex){}
        throw new HttpException("STATUSCODE!=200");
    }
}
项目:android-aosp-mms    文件:HttpUtils.java   
private static AndroidHttpClient createHttpClient(Context context) {
    String userAgent = MmsConfig.getUserAgent();
    AndroidHttpClient client = AndroidHttpClient.newInstance(userAgent, context);
    HttpParams params = client.getParams();
    HttpProtocolParams.setContentCharset(params, "UTF-8");

    // set the socket timeout
    int soTimeout = MmsConfig.getHttpSocketTimeout();

    if (Log.isLoggable(LogTag.TRANSACTION, Log.DEBUG)) {
        Log.d(TAG, "[HttpUtils] createHttpClient w/ socket timeout " + soTimeout + " ms, "
                + ", UA=" + userAgent);
    }
    HttpConnectionParams.setSoTimeout(params, soTimeout);
    return client;
}
项目:android_xcore    文件:HttpAndroidDataSource.java   
public InputStream getInputSteam(HttpUriRequest request) throws IllegalStateException, IOException {
    request.setHeader(ACCEPT_KEY, ACCEPT_DEFAULT_VALUE);
    request.setHeader(USER_AGENT_KEY, sUserAgent);
    AndroidHttpClient.modifyRequestToAcceptGzipResponse(request);
    Log.xd(this, request);
       HttpClient client = mInputStreamHelper.getClient();
       HttpResponse response = client.execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
       boolean isRedirect = isRedirect(statusCode);
       if (isRedirect) {
        Header firstHeader = response.getFirstHeader("Location");
        if (firstHeader != null) {
               String value = firstHeader.getValue();
               if (!StringUtil.isEmpty(value) && !value.equals(request.getURI().toString())) {
                   return createRedirectRequest(request, response, value);
               }
        }
    }
    if (mResponseStatusHandler != null) {
        mResponseStatusHandler.statusHandle(this, request, response);
    }
    HttpEntity httpEntity = response.getEntity();
       InputStream ungzippedContent = AndroidHttpClient.getUngzippedContent(httpEntity);
       return mInputStreamHelper.getInputStream(ungzippedContent, client);
}
项目:Slideshow-for-GTV    文件:Utils.java   
/**
 * Check if a URL is valid and points to a resource on the remote web
 * server. Used to check if certain image sizes are available.
 * 
 * @param url
 * @return
 */
public static boolean checkUrl(String url) {
    Log.d(LOG_TAG, "checkUrl: " + url);
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet request = new HttpGet(url);
    try {
        HttpResponse response = client.execute(request);
        final int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            return true;
        }
    } catch (Exception e) {
        request.abort();
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return false;
}
项目:TflTravelAlerts    文件:BackendConnection.java   
private static BackendConnectionResult doRequest(HttpUriRequest request) {
    RequestAnalytics analytics = new RequestAnalytics(request);
    AndroidHttpClient httpClient = AndroidHttpClient.newInstance(userAgent);
    BackendConnectionResult result;
    try {
        HttpResponse response = httpClient.execute(request);
        InputStream inputStream = response.getEntity().getContent();
        StatusLine statusLine = response.getStatusLine();

        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charsets.UTF_8);
        String contentString = CharStreams.toString(inputStreamReader);
        inputStreamReader.close();

        httpClient.close();
        result = new BackendConnectionResult(statusLine, contentString);
    } catch (IOException e) {
        result = new BackendConnectionResult(e);
    }
    analytics.done(result);
    return result;
}
项目:iosched2013    文件:ImageLoader.java   
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(
                UIUtils.hasHoneycomb() ?
                        new HurlStack() :
                        new HttpClientStack(AndroidHttpClient.newInstance(
                                NetUtils.getUserAgent(context))));

        Cache cache = new DiskBasedCache(getDiskCacheDir(context, CACHE_DIR));
        RequestQueue queue = new RequestQueue(cache, network);
        queue.start();
        return queue;
    }
项目:GitHub    文件:Volley.java   
/**
 * 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;
}
项目:Codeforces    文件:Volley.java   
/**
 * 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;
}
项目:iosched-reader    文件:Volley.java   
/**
 * 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;
}
项目:PlusGram    文件:Volley.java   
/**
 * 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.
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }

    Network network = new BasicNetwork(stack);

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

    return queue;
}
项目:VoV    文件:Volley.java   
/**
 * 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;
}
项目:core-http    文件:Volley.java   
/**
 * Creates a default instance of the worker pool and calls {@link RequestLauncher#start()} on it.
 * You may set a maximum size of the disk cache in bytes.
 *
 * @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.
 * @param maxDiskCacheBytes the maximum size of the disk cache, in bytes. Use -1 for default size.
 * @return A started {@link RequestLauncher} instance.
 */
public static RequestLauncher newLauncher(Context context, HttpStack stack, int maxDiskCacheBytes) {
    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) {
        e.printStackTrace();
    }

    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);

    RequestLauncher launcher;
    if (maxDiskCacheBytes <= -1) {
        // No maximum size specified
        launcher = new RequestLauncher(new DiskBasedCache(cacheDir), network);
    } else {
        // Disk cache size specified
        launcher = new RequestLauncher(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
    }
    launcher.start();

    return launcher;
}
项目:smconf-android    文件:Volley.java   
/**
 * 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;
}