Search in sources :

Example 96 with DefaultHttpClient

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

the class IoUtils method responseFromServiceByPost.

public static String responseFromServiceByPost(String url, String encode, HashMap<String, String> map, RequestCallBack requestCallBack) {
    if (url == null || url.equals("") || map == null) {
        return null;
    }
    if (requestCallBack != null) {
        requestCallBack.onRequestStart();
    }
    Log.d(TAG_LISTLOGIC, "post数据请求地址:" + url);
    if (requestCallBack != null) {
        requestCallBack.onRequestLoading();
    }
    HttpPost httpPost = null;
    URI encodedUri = null;
    try {
        encodedUri = new URI(url);
        httpPost = new HttpPost(encodedUri);
    } catch (URISyntaxException e) {
        // 清理一些空格
        String encodedUrl = url.replace(' ', '+');
        httpPost = new HttpPost(encodedUrl);
        e.printStackTrace();
    }
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEF_SOCKET_TIMEOUT);
    try {
        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, encode));
        // httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,
        // "GBK"));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        if (httpResponse != null) {
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity).trim();
                Log.d(TAG_LISTLOGIC, "post数据请求服务器返回值200");
                Log.d(TAG_LISTLOGIC, "post返回值:" + result);
                if (requestCallBack != null) {
                    requestCallBack.onRequestSuccess(result);
                }
                return result;
            } else {
                httpPost.abort();
                if (requestCallBack != null) {
                    requestCallBack.onRequestError(RequestCallBack.HTTPSTATUSERROR, "HTTP链接错误");
                }
            }
        } else {
            httpPost.abort();
            if (requestCallBack != null) {
                requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
        }
        return null;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        if (requestCallBack != null) {
            requestCallBack.onRequestError(RequestCallBack.OUTOFMEMORYERROR, "内存溢出");
        }
        return null;
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
        if (requestCallBack != null) {
            requestCallBack.onCancel();
        }
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) URISyntaxException(java.net.URISyntaxException) 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 97 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project Android by hmkcode.

the class MainActivity method GET.

public static String GET(String url) {
    InputStream inputStream = null;
    String result = "";
    try {
        // create HttpClient
        HttpClient httpclient = new DefaultHttpClient();
        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        // receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();
        // convert inputstream to string
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
    return result;
}
Also used : InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) JSONException(org.json.JSONException)

Example 98 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project android-player-samples by BrightcoveOS.

the class MainActivity method httpGet.

public String httpGet(String url) {
    String domain = getResources().getString(R.string.ais_domain);
    String result = "";
    CookieStore cookieStore = new BasicCookieStore();
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    // If we have a cookie stored, parse and use it. Otherwise, use a default http client.
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        if (!authorizationCookie.equals("")) {
            String[] cookies = authorizationCookie.split(";");
            for (int i = 0; i < cookies.length; i++) {
                String[] kvp = cookies[i].split("=");
                if (kvp.length != 2) {
                    throw new Exception("Illegal cookie: missing key/value pair.");
                }
                BasicClientCookie c = new BasicClientCookie(kvp[0], kvp[1]);
                c.setDomain(domain);
                cookieStore.addCookie(c);
            }
        }
        HttpResponse httpResponse = httpClient.execute(httpGet, localContext);
        result = EntityUtils.toString(httpResponse.getEntity());
    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage());
    }
    return result;
}
Also used : CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicClientCookie(org.apache.http.impl.cookie.BasicClientCookie) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 99 with DefaultHttpClient

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

the class HttpUtils method getResponseFromGetUrl.

public static String getResponseFromGetUrl(String url, String params) throws Exception {
    Log.d("Chen", "url--" + url);
    if (null != params && !"".equals(params)) {
        url = url + "?";
        String[] paramarray = params.split(",");
        for (int index = 0; null != paramarray && index < paramarray.length; index++) {
            if (index == 0) {
                url = url + paramarray[index];
            } else {
                url = url + "&" + paramarray[index];
            }
        }
    }
    HttpGet httpRequest = new HttpGet(url);
    //        httpRequest.addHeader("Cookie", logininfo);
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = 30000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 30000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    // DefaultHttpClient httpclient = new DefaultHttpClient();
    StringBuffer sb = new StringBuffer();
    try {
        HttpResponse httpResponse = httpclient.execute(httpRequest);
        String inputLine = "";
        // Log.d("Chen","httpResponse.getStatusLine().getStatusCode()"+httpResponse.getStatusLine().getStatusCode());
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            InputStreamReader is = new InputStreamReader(httpResponse.getEntity().getContent());
            BufferedReader in = new BufferedReader(is);
            while ((inputLine = in.readLine()) != null) {
                sb.append(inputLine);
            }
            in.close();
        } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
            return "";
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return sb.toString();
}
Also used : InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) BufferedReader(java.io.BufferedReader) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 100 with DefaultHttpClient

use of org.apache.http.impl.client.DefaultHttpClient in project nhin-d by DirectProject.

the class HttpClientFactory method createHttpClient.

/**
	 * Creates an HttpClient with the default connection timeout and SO timeout.
	 * @return The HTTP client.
	 */
public static HttpClient createHttpClient() {
    final HttpClient client = new DefaultHttpClient(conMgr);
    final HttpParams httpParams = client.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_CON_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_SO_TIMEOUT);
    return client;
}
Also used : HttpParams(org.apache.http.params.HttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

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