Search in sources :

Example 41 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project UltimateAndroid by cymcsg.

the class CommonHttpClient method getNewInstance.

// 每次返回同一实例
// public static synchronized HttpClient getInstance(Context mContext){
//
// if(null == singleStance){
// singleStance = getNewInstance(mContext);
// }
// return singleStance ;
// }
// 每次都返回新的HttpClient实例
public static HttpClient getNewInstance(Context mContext) {
    HttpClient newInstance;
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);
    // 自定义三个timeout参数
    /*
         * 1.set a timeout for the connection manager,it defines how long we
		 * should wait to get a connection out of the connection pool managed by
		 * the connection manager
		 */
    ConnManagerParams.setTimeout(params, 5000);
    /*
         * 2.The second timeout value defines how long we should wait to make a
		 * connection over the network to the server on the other end
		 */
    HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);
    /*
         * 3.we set a socket timeout value to 4 seconds to define how long we
		 * should wait to get data back for our request.
		 */
    HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET);
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
    newInstance = new DefaultHttpClient(conMgr, params);
    switch(checkNetworkTypeDeprecated(mContext)) {
        case TYPE_CT_WAP:
            {
                // 通过代理解决中国移动联通GPRS中wap无法访问的问题
                HttpHost proxy = new HttpHost("10.0.0.200", 80, "http");
                newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.200访问www");
            }
            break;
        case TYPE_CM_CU_WAP:
            {
                // 通过代理解决中国移动联通GPRS中wap无法访问的问题
                HttpHost proxy = new HttpHost("10.0.0.172", 80, "http");
                newInstance.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                Logs.v("当前网络类型为cm_cu_wap,设置代理10.0.0.172访问www");
            }
            break;
    }
    return newInstance;
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) HttpHost(org.apache.http.HttpHost) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 42 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project UltimateAndroid by cymcsg.

the class HttpUtils method uploadFilesMPE.

/**
     * Update Files via Multipart
     *
     * @param url
     * @param paramsList
     * @param fileParams
     * @param file
     * @param files
     * @return status
     * @deprecated
     */
public static String uploadFilesMPE(String url, List<NameValuePair> paramsList, String fileParams, File file, File... files) {
    String result = "";
    try {
        DefaultHttpClient mHttpClient;
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
        mHttpClient = new DefaultHttpClient(params);
        HttpPost httpPost = new HttpPost(url);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (BasicUtils.judgeNotNull(paramsList)) {
            for (NameValuePair nameValuePair : paramsList) {
                multipartEntity.addPart(nameValuePair.getName(), new StringBody(nameValuePair.getValue()));
            }
        }
        multipartEntity.addPart(fileParams, new FileBody(file));
        for (File f : files) {
            multipartEntity.addPart(fileParams, new FileBody(f));
        }
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResp = mHttpClient.execute(httpPost);
        // 判断是够请求成功
        if (httpResp.getStatusLine().getStatusCode() == 200) {
            // 获取返回的数据
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Logs.d("HttpPost success :");
            Logs.d(result);
        } else {
            Logs.d("HttpPost failed" + "    " + httpResp.getStatusLine().getStatusCode() + "   " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
            result = "HttpPost failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "ConnectTimeoutException";
        Logs.e("HttpPost overtime:  " + "");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        result = "Exception";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 43 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project mobile-android by photo.

the class ApiBase method execute.

/**
     * Execute a request to the API.
     * 
     * @param request request to perform
     * @param baseUrl the base server url
     * @param consumer the oauth consumer key to sign request
     * @param listener Progress Listener with callback on progress
     * @param connectionTimeout the connection and socket timeout
     * @return the response from the API
     * @throws ClientProtocolException
     * @throws IOException
     */
public ApiResponse execute(ApiRequest request, String baseUrl, OAuthConsumer consumer, ProgressListener listener, int connectionTimeout) throws ClientProtocolException, IOException {
    // PoolingClientConnectionManager();
    HttpParams params = new BasicHttpParams();
    // set params for connection...
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, connectionTimeout);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    DefaultHttpClient httpClient = new DefaultHttpClient(params);
    HttpUriRequest httpRequest = createHttpRequest(request, baseUrl, listener);
    httpRequest.getParams().setBooleanParameter("http.protocol.expect-continue", false);
    httpRequest.setHeader("User-Agent", "android");
    httpRequest.setHeader("source", "android");
    if (consumer != null) {
        try {
            consumer.sign(httpRequest);
        } catch (Exception e) {
            GuiUtils.noAlertError(TAG, "Error signing request", e);
        }
    } else {
        TrackerUtils.trackBackgroundEvent("not_signed_request", baseUrl + request.getPath());
    }
    return new ApiResponse(baseUrl + request.getPath(), httpClient.execute(httpRequest));
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicHttpParams(org.apache.http.params.BasicHttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 44 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project openhab1-addons by openhab.

the class HubIOStream method open.

@Override
public boolean open() {
    m_client = new DefaultHttpClient();
    if (m_user != null && m_pass != null) {
        m_client.getCredentialsProvider().setCredentials(new AuthScope(m_host, m_port), new UsernamePasswordCredentials(m_user, m_pass));
    }
    HttpConnectionParams.setConnectionTimeout(m_client.getParams(), 5000);
    m_in = new HubInputStream();
    m_pollThread = new Thread(this);
    m_pollThread.start();
    m_out = new HubOutputStream();
    return true;
}
Also used : AuthScope(org.apache.http.auth.AuthScope) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 45 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project ignition by mttkay.

the class IgnitedHttp method setupHttpClient.

protected void setupHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();
    ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_FOR_CONNECTION_TIMEOUT);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_CONNECTIONS));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SOCKET_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, DEFAULT_HTTP_USER_AGENT);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    if (IgnitedDiagnostics.ANDROID_API_LEVEL >= 7) {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    } else {
        // used to work around a bug in Android 1.6:
        // http://code.google.com/p/android/issues/detail?id=1946
        // TODO: is there a less rigorous workaround for this?
        schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    }
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    httpClient = new DefaultHttpClient(cm, httpParams);
}
Also used : Scheme(org.apache.http.conn.scheme.Scheme) ThreadSafeClientConnManager(org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) EasySSLSocketFactory(com.github.ignition.support.http.ssl.EasySSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams) ConnPerRouteBean(org.apache.http.conn.params.ConnPerRouteBean) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)481 HttpResponse (org.apache.http.HttpResponse)293 HttpGet (org.apache.http.client.methods.HttpGet)227 HttpClient (org.apache.http.client.HttpClient)203 IOException (java.io.IOException)158 HttpPost (org.apache.http.client.methods.HttpPost)107 Test (org.junit.Test)86 HttpEntity (org.apache.http.HttpEntity)84 ClientProtocolException (org.apache.http.client.ClientProtocolException)64 InputStream (java.io.InputStream)60 Scheme (org.apache.http.conn.scheme.Scheme)53 BasicHttpParams (org.apache.http.params.BasicHttpParams)51 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)49 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)48 HttpParams (org.apache.http.params.HttpParams)47 ArrayList (java.util.ArrayList)45 URI (java.net.URI)43 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)38 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)38 InputStreamReader (java.io.InputStreamReader)37