Search in sources :

Example 46 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project FastDev4Android by jiangqqlmj.

the class IoUtils method responseFromServiceByGetNo.

/**
     * get请求获取服务端数据 不适用账号密码验证
     */
public static String responseFromServiceByGetNo(String url, HashMap<String, String> map) {
    if (url == null || url.equals("")) {
        return null;
    }
    if (map != null) {
        StringBuilder sb = new StringBuilder(url);
        sb.append('?');
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey().toString();
            String value = null;
            if (entry.getValue() == null) {
                value = "";
            } else {
                value = entry.getValue().toString();
            }
            sb.append(key);
            sb.append('=');
            try {
                Log.d(TAG_LISTLOGIC, "get获取数据的key:" + key);
                Log.d(TAG_LISTLOGIC, "get获取数据的value:" + value);
                value = URLEncoder.encode(value, HTTP.UTF_8);
                Log.d(TAG_LISTLOGIC, "get投递编码后value:" + value);
                sb.append(value);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            sb.append('&');
        }
        // 删除最后一个"&"
        sb.deleteCharAt(sb.length() - 1);
        url = sb.toString();
    }
    Log.d(TAG_LISTLOGIC, "get请求地址" + url);
    HttpGet httpGet = null;
    URI encodedUri = null;
    InputStream is = null;
    try {
        encodedUri = new URI(url);
        httpGet = new HttpGet(encodedUri);
    } catch (URISyntaxException e) {
        // 清理一些空格
        String encodedUrl = url.replace(' ', '+');
        httpGet = new HttpGet(encodedUrl);
        e.printStackTrace();
    }
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 4000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 4000);
    try {
        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse != null) {
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpStatus.SC_OK) {
                HttpEntity entity = httpResponse.getEntity();
                Header header = httpResponse.getFirstHeader("Content-Encoding");
                if (header != null && header.getValue().equals("gzip")) {
                    Log.d(TAG_LISTLOGIC, "数据已做gzip压缩...");
                    // gzip压缩
                    byte[] resultstream = EntityUtils.toByteArray(entity);
                    resultstream = unGZip(resultstream);
                    return new String(resultstream, "UTF-8");
                } else {
                    Log.d(TAG_LISTLOGIC, "数据无Gzip压缩...");
                    // 无压缩
                    is = entity.getContent();
                    if (is != null) {
                        return new String(getByteArrayFromInputstream(is), "utf-8");
                    }
                }
                Log.d(TAG_LISTLOGIC, "get请求服务器返回值200");
            } else {
                httpGet.abort();
            }
        } else {
            httpGet.abort();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        return null;
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DataInputStream(java.io.DataInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Header(org.apache.http.Header) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HashMap(java.util.HashMap) Map(java.util.Map)

Example 47 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project FastDev4Android by jiangqqlmj.

the class IoUtils method getInputStreamFromUrl.

public static InputStream getInputStreamFromUrl(String url, RequestCallBack requestCallBack) {
    if (url == null || !url.contains("http://")) {
        Log.e("listlogic", "列表下载地址异常");
        return null;
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestStart();
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestLoading();
    }
    URI encodedUri = null;
    HttpGet httpGet = null;
    try {
        encodedUri = new URI(url);
        httpGet = new HttpGet(encodedUri);
    } catch (URISyntaxException e) {
        // 清理一些空格
        String encodedUrl = url.replace(' ', '+');
        httpGet = new HttpGet(encodedUrl);
        e.printStackTrace();
    }
    // 创建httpclient对象
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEF_SOCKET_TIMEOUT);
    HttpResponse httpResponse = null;
    InputStream inputStream = null;
    try {
        try {
            // 执行请求
            httpResponse = httpClient.execute(httpGet);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        if (httpResponse != null) {
            int httpCode = httpResponse.getStatusLine().getStatusCode();
            if (httpCode == HttpStatus.SC_OK) {
                // 请求数据
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    inputStream = httpEntity.getContent();
                    byte[] bytes = getByteArrayFromInputstream(inputStream);
                    if (bytes != null) {
                        InputStream inputStream2 = new ByteArrayInputStream(bytes);
                        if (requestCallBack != null) {
                            requestCallBack.onRequestSuccess(inputStream2);
                        }
                        return inputStream2;
                    }
                }
            } else {
                httpGet.abort();
                if (requestCallBack != null) {
                    requestCallBack.onRequestError(RequestCallBack.HTTPSTATUSERROR, "HTTP链接错误");
                }
            }
        } else {
            httpGet.abort();
            if (requestCallBack != null) {
                requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
    } catch (IOException e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (requestCallBack != null) {
            requestCallBack.onCancel();
        }
    }
    return null;
}
Also used : SocketException(java.net.SocketException) UnknownHostException(java.net.UnknownHostException) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DataInputStream(java.io.DataInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) ByteArrayInputStream(java.io.ByteArrayInputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient)

Example 48 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project FastDev4Android by jiangqqlmj.

the class IoUtils method sendMessageByPost.

/**
     * post投递
     */
public static void sendMessageByPost(String url, HashMap<String, String> map) {
    if (url == null || url.equals("")) {
        return;
    }
    Log.d(TAG_LISTLOGIC, "post投递地址:" + url);
    HttpPost httpPost = null;
    URI encodedUri = getEncodingURI(url);
    httpPost = new HttpPost(encodedUri);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DELIVER_CONN_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DELIVER_SOCKET_TIMEOUT);
    try {
        if (map != null) {
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : map.entrySet()) {
                String key = entry.getKey().toString();
                String value = null;
                if (entry.getValue() == null) {
                    value = "";
                } else {
                    value = entry.getValue().toString();
                }
                Log.d(TAG_LISTLOGIC, "post投递参数" + key + "=" + value);
                BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, value);
                nameValuePair.add(basicNameValuePair);
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
        }
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse != null) {
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                Log.d(TAG_LISTLOGIC, "post投递服务器返回200");
                return;
            } else {
                httpPost.abort();
            }
        } else {
            httpPost.abort();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map)

Example 49 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project FastDev4Android by jiangqqlmj.

the class IoUtils method getInputStream.

/**
     * 获取url的InputStream
     *
     * @param urlStr
     * @return
     */
public static InputStream getInputStream(String urlStr) {
    Log.d(TAG_LISTLOGIC, "get http input:" + urlStr);
    InputStream inpStream = null;
    try {
        HttpGet http = new HttpGet(urlStr);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) client.execute(http);
        HttpEntity httpEntity = response.getEntity();
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
        // 获取数据流
        inpStream = bufferedHttpEntity.getContent();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (inpStream != null) {
            try {
                inpStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    return inpStream;
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DataInputStream(java.io.DataInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 50 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project SmartAndroidSource by jaychou2012.

the class MySSLSocketFactory method getNewHttpClient.

/**
     * Gets a DefaultHttpClient which trusts a set of certificates specified by the KeyStore
     *
     * @param keyStore custom provided KeyStore instance
     * @return DefaultHttpClient
     */
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
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) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory) BasicHttpParams(org.apache.http.params.BasicHttpParams) ClientConnectionManager(org.apache.http.conn.ClientConnectionManager) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)342 HttpResponse (org.apache.http.HttpResponse)199 HttpGet (org.apache.http.client.methods.HttpGet)167 HttpClient (org.apache.http.client.HttpClient)139 IOException (java.io.IOException)104 Test (org.junit.Test)65 HttpPost (org.apache.http.client.methods.HttpPost)64 HttpEntity (org.apache.http.HttpEntity)55 BasicHttpParams (org.apache.http.params.BasicHttpParams)49 ClientProtocolException (org.apache.http.client.ClientProtocolException)48 InputStream (java.io.InputStream)47 HttpParams (org.apache.http.params.HttpParams)43 Scheme (org.apache.http.conn.scheme.Scheme)39 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)38 ArrayList (java.util.ArrayList)32 URI (java.net.URI)30 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)30 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)29 InputStreamReader (java.io.InputStreamReader)28 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)27