Example usage for org.apache.http.client HttpClient getParams

List of usage examples for org.apache.http.client HttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient getParams.

Prototype

@Deprecated
HttpParams getParams();

Source Link

Document

Obtains the parameters for this client.

Usage

From source file:com.easyhome.common.modules.network.HttpManager.java

/**
 * ? URL ?/*ww  w. j av  a 2  s  .com*/
 * 
 * @param url    ?
 * @param method "GET" or "POST"
 * @param params ?
 * @param file    ????? SdCard ?
 * 
 * @return ?
 * @throws com.sina.weibo.sdk.exception.WeiboException ?
 */
public static String openUrl(String url, String method, WeiboParameters params, String file)
        throws WeiboException {
    String result = "";
    try {
        HttpClient client = getNewHttpClient();
        HttpUriRequest request = null;
        ByteArrayOutputStream bos = null;
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN());
        if (method.equals(HTTPMETHOD_GET)) {
            url = url + "?" + Utility.encodeUrl(params);
            HttpGet get = new HttpGet(url);
            request = get;
        } else if (method.equals(HTTPMETHOD_POST)) {
            HttpPost post = new HttpPost(url);
            request = post;
            byte[] data = null;
            String _contentType = params.getValue("content-type");

            bos = new ByteArrayOutputStream();
            if (!TextUtils.isEmpty(file)) {
                paramToUpload(bos, params);
                post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
                // ?
                // Utility.UploadImageUtils.revitionPostImageSize(file);
                imageContentToUpload(bos, file);
            } else {
                if (_contentType != null) {
                    params.remove("content-type");
                    post.setHeader("Content-Type", _contentType);
                } else {
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                }

                String postParam = Utility.encodeParameters(params);
                data = postParam.getBytes("UTF-8");
                bos.write(data);
            }
            data = bos.toByteArray();
            bos.close();
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(url);
        }
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if (statusCode != 200) {
            result = readHttpResponse(response);
            throw new WeiboException(result);
        }
        result = readHttpResponse(response);
        return result;
    } catch (IOException e) {
        throw new WeiboException(e);
    }
}

From source file:com.easyhome.common.modules.network.HttpManager.java

/**
 * ???? formdata name="pic"  name="file" ?????
 * /*from  ww w  .j a  va 2  s. c  o  m*/
 * @param url    ?
 * @param method "GET" or "POST"
 * @param params ?
 * @param file   ????? SdCard ?
 * 
 * @return ?
 * @throws com.sina.weibo.sdk.exception.WeiboException ?
 */
public static String uploadFile(String url, String method, WeiboParameters params, String file)
        throws WeiboException {
    String result = "";
    try {
        HttpClient client = getNewHttpClient();
        HttpUriRequest request = null;
        ByteArrayOutputStream bos = null;
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN());
        if (method.equals(HTTPMETHOD_GET)) {
            url = url + "?" + Utility.encodeUrl(params);
            HttpGet get = new HttpGet(url);
            request = get;
        } else if (method.equals(HTTPMETHOD_POST)) {
            HttpPost post = new HttpPost(url);
            request = post;
            byte[] data = null;
            String _contentType = params.getValue("content-type");

            bos = new ByteArrayOutputStream();
            if (!TextUtils.isEmpty(file)) {
                paramToUpload(bos, params);
                post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
                // ?
                // Utility.UploadImageUtils.revitionPostImageSize(file);
                fileToUpload(bos, file);
            } else {
                if (_contentType != null) {
                    params.remove("content-type");
                    post.setHeader("Content-Type", _contentType);
                } else {
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                }

                String postParam = Utility.encodeParameters(params);
                data = postParam.getBytes("UTF-8");
                bos.write(data);
            }
            data = bos.toByteArray();
            bos.close();
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(url);
        }
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if (statusCode != 200) {
            result = readHttpResponse(response);
            throw new WeiboException(result);
        }
        result = readHttpResponse(response);
        return result;
    } catch (IOException e) {
        throw new WeiboException(e);
    }
}

From source file:com.easyhome.common.modules.network.HttpManager.java

/**
 * ? URL ?/*from  w  w w  .  j a  v a  2 s .c  o m*/
 *
 * @param url     ?
 * @param method  "GET" or "POST"
 * @param params  ?
 * @param fileContent ?
 *
 * @return ?
 * @throws com.sina.weibo.sdk.exception.WeiboException ?
 */
public static String openUrl4Byte(String url, String method, WeiboParameters params, byte[] fileContent)
        throws WeiboException {
    String result = null;
    try {
        HttpClient client = getNewHttpClient();
        HttpUriRequest request = null;
        ByteArrayOutputStream bos = null;
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN());
        if (method.equals(HTTPMETHOD_GET)) {
            url = url + "?" + Utility.encodeUrl(params);
            HttpGet get = new HttpGet(url);
            request = get;
        } else if (method.equals(HTTPMETHOD_POST)) {
            HttpPost post = new HttpPost(url);
            request = post;
            byte[] data = null;
            String _contentType = params.getValue("content-type");

            bos = new ByteArrayOutputStream();
            if (fileContent != null && fileContent.length > 0) {
                paramToUpload(bos, params);
                post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
                imageContentToUpload4Byte(bos, fileContent);
            } else {
                if (_contentType != null) {
                    params.remove("content-type");
                    post.setHeader("Content-Type", _contentType);
                } else {
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                }

                String postParam = Utility.encodeParameters(params);
                data = postParam.getBytes("UTF-8");
                bos.write(data);
            }
            data = bos.toByteArray();
            bos.close();
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(url);
        }
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if (statusCode != 200) {
            String resultStr = readHttpResponse(response);
            throw new WeiboException(resultStr);
        }
        result = readHttpResponse(response);
        return result;
    } catch (IOException e) {
        throw new WeiboException(e);
    } catch (Exception e) {
        throw new WeiboException(e);
    }
}

From source file:com.gimranov.zandy.app.task.ZoteroAPITask.java

/**
 * Executes the specified APIRequest and handles the response
 * //from   w  w  w . j a v a2 s. co m
 * This is done synchronously; use the the AsyncTask interface for calls
 * from the UI thread.
 * 
 * @param req
 * @return
 */
public static String issue(APIRequest req, Database db) {
    // Check that the method makes sense
    String method = req.method.toLowerCase();
    if (!method.equals("get") && !method.equals("post") && !method.equals("delete") && !method.equals("put")) {
        // TODO Throw an exception here.
        Log.e(TAG, "Invalid method: " + method);
        return null;
    }
    String resp = "";
    try {
        // Append content=json everywhere, if we don't have it yet
        if (req.query.indexOf("content=json") == -1) {
            if (req.query.indexOf("?") != -1) {
                req.query += "&content=json";
            } else {
                req.query += "?content=json";
            }
        }

        // Append the key, if defined, to all requests
        if (req.key != null && req.key != "") {
            req.query += "&key=" + req.key;

        }
        if (method.equals("put")) {
            req.query = req.query.replace("content=json&", "");
        }
        Log.i(TAG, "Request " + req.method + ": " + req.query);

        URI uri = new URI(req.query);
        HttpClient client = new DefaultHttpClient();
        // The default implementation includes an Expect: header, which
        // confuses the Zotero servers.
        client.getParams().setParameter("http.protocol.expect-continue", false);
        // We also need to send our data nice and raw.
        client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

        /* It would be good to rework this mess to be less repetitive */
        if (method.equals("post")) {
            HttpPost request = new HttpPost();
            request.setURI(uri);

            // Set headers if necessary
            if (req.ifMatch != null) {
                request.setHeader("If-Match", req.ifMatch);
            }
            if (req.contentType != null) {
                request.setHeader("Content-Type", req.contentType);
            }
            if (req.body != null) {
                Log.d(TAG, "Post body: " + req.body);
                // Force the encoding here
                StringEntity entity = new StringEntity(req.body, "UTF-8");
                request.setEntity(entity);
            }
            if (req.disposition.equals("xml")) {
                HttpResponse hr = client.execute(request);
                int code = hr.getStatusLine().getStatusCode();
                Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase());
                if (code < 400) {
                    HttpEntity he = hr.getEntity();
                    InputStream in = he.getContent();
                    XMLResponseParser parse = new XMLResponseParser(in);
                    if (req.updateKey != null && req.updateType != null)
                        parse.update(req.updateType, req.updateKey);
                    // The response on POST in XML mode (new item) is a feed
                    parse.parse(XMLResponseParser.MODE_FEED, uri.toString(), db);
                    resp = "XML was parsed.";
                } else {
                    Log.e(TAG, "Not parsing non-XML response, code >= 400");
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(ostream);
                    Log.e(TAG, "Error Body: " + ostream.toString());
                    Log.e(TAG, "Post Body:" + req.body);
                }
            } else {
                BasicResponseHandler brh = new BasicResponseHandler();
                try {
                    resp = client.execute(request, brh);
                    req.onSuccess(db);
                } catch (ClientProtocolException e) {
                    Log.e(TAG, "Exception thrown issuing POST request: ", e);
                    req.onFailure(db);
                }
            }
        } else if (method.equals("put")) {
            HttpPut request = new HttpPut();
            request.setURI(uri);

            // Set headers if necessary
            if (req.ifMatch != null) {
                request.setHeader("If-Match", req.ifMatch);
            }
            if (req.contentType != null) {
                request.setHeader("Content-Type", req.contentType);
            }
            if (req.body != null) {
                // Force the encoding here
                StringEntity entity = new StringEntity(req.body, "UTF-8");
                request.setEntity(entity);
            }
            if (req.disposition.equals("xml")) {
                HttpResponse hr = client.execute(request);
                int code = hr.getStatusLine().getStatusCode();
                Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase());
                if (code < 400) {
                    HttpEntity he = hr.getEntity();
                    InputStream in = he.getContent();
                    XMLResponseParser parse = new XMLResponseParser(in);
                    parse.parse(XMLResponseParser.MODE_ENTRY, uri.toString(), db);
                    resp = "XML was parsed.";
                    // TODO
                    req.onSuccess(db);
                } else {
                    Log.e(TAG, "Not parsing non-XML response, code >= 400");
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(ostream);
                    Log.e(TAG, "Error Body: " + ostream.toString());
                    Log.e(TAG, "Put Body:" + req.body);
                    // TODO
                    req.onFailure(db);
                    // "Precondition Failed"
                    // The item changed server-side, so we have a conflict to resolve...
                    // XXX This is a hard problem.
                    if (code == 412) {
                        Log.e(TAG, "Skipping dirtied item with server-side changes as well");
                    }
                }
            } else {
                BasicResponseHandler brh = new BasicResponseHandler();
                try {
                    resp = client.execute(request, brh);
                    req.onSuccess(db);
                } catch (ClientProtocolException e) {
                    Log.e(TAG, "Exception thrown issuing PUT request: ", e);
                    req.onFailure(db);
                }
            }
        } else if (method.equals("delete")) {
            HttpDelete request = new HttpDelete();
            request.setURI(uri);
            if (req.ifMatch != null) {
                request.setHeader("If-Match", req.ifMatch);
            }

            BasicResponseHandler brh = new BasicResponseHandler();
            try {
                resp = client.execute(request, brh);
                req.onSuccess(db);
            } catch (ClientProtocolException e) {
                Log.e(TAG, "Exception thrown issuing DELETE request: ", e);
                req.onFailure(db);
            }
        } else {
            HttpGet request = new HttpGet();
            request.setURI(uri);
            if (req.contentType != null) {
                request.setHeader("Content-Type", req.contentType);
            }
            if (req.disposition.equals("xml")) {
                HttpResponse hr = client.execute(request);
                int code = hr.getStatusLine().getStatusCode();
                Log.d(TAG, code + " : " + hr.getStatusLine().getReasonPhrase());
                if (code < 400) {
                    HttpEntity he = hr.getEntity();
                    InputStream in = he.getContent();
                    XMLResponseParser parse = new XMLResponseParser(in);
                    // We can tell from the URL whether we have a single item or a feed
                    int mode = (uri.toString().indexOf("/items?") == -1 && uri.toString().indexOf("/top?") == -1
                            && uri.toString().indexOf("/collections?") == -1
                            && uri.toString().indexOf("/children?") == -1) ? XMLResponseParser.MODE_ENTRY
                                    : XMLResponseParser.MODE_FEED;
                    parse.parse(mode, uri.toString(), db);
                    resp = "XML was parsed.";
                    // TODO
                    req.onSuccess(db);
                } else {
                    Log.e(TAG, "Not parsing non-XML response, code >= 400");
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    hr.getEntity().writeTo(ostream);
                    Log.e(TAG, "Error Body: " + ostream.toString());
                    Log.e(TAG, "Put Body:" + req.body);
                    // TODO
                    req.onFailure(db);
                    // "Precondition Failed"
                    // The item changed server-side, so we have a conflict to resolve...
                    // XXX This is a hard problem.
                    if (code == 412) {
                        Log.e(TAG, "Skipping dirtied item with server-side changes as well");
                    }
                }
            } else {
                BasicResponseHandler brh = new BasicResponseHandler();
                try {
                    resp = client.execute(request, brh);
                    req.onSuccess(db);
                } catch (ClientProtocolException e) {
                    Log.e(TAG, "Exception thrown issuing GET request: ", e);
                    req.onFailure(db);
                }
            }
        }
        Log.i(TAG, "Response: " + resp);
    } catch (IOException e) {
        Log.e(TAG, "Connection error", e);
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI error", e);
    }
    return resp;
}

From source file:topoos.APIAccess.APICaller.java

/**
 * Initiates an operation on topoos API.
 * /*from  w  w w  .j a va  2s.c  o m*/
 * @param operation
 *            Represents the operation to be executed
 * @param result
 *            Represents a result returned from a query to API topoos
 * @throws IOException
 * @throws TopoosException
 */
public static void ExecuteOperation(APIOperation operation, APICallResult result)
        throws IOException, TopoosException {
    HttpClient hc = new DefaultHttpClient();
    if (!operation.ValidateParams())
        throw new TopoosException(TopoosException.NOT_VALID_PARAMS);
    String OpURI = Constants.TOPOOSURIAPI + operation.ConcatParams();
    if (Constants.DEBUGURL) {
        Log.d(Constants.TAG, OpURI);
        //         appendLog(OpURI);
    }
    HttpPost post = new HttpPost(OpURI);
    // POST
    if (operation.getMethod().equals("POST")) {
        post.setEntity(operation.BodyParams());
    }
    HttpResponse rp = hc.execute(post);
    HttpParams httpParams = hc.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, Constants.HTTP_WAITING_MILISECONDS);
    if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        result.setResult(EntityUtils.toString(rp.getEntity()));
        if (Constants.DEBUGURL) {
            Log.d(Constants.TAG, result.getResult());
            //            appendLog(result.getResult());
        }
        result.setError(null);
        result.setParameters();
    } else {
        switch (rp.getStatusLine().getStatusCode()) {
        case 400:
            throw new TopoosException(TopoosException.ERROR400);
        case 405:
            throw new TopoosException(TopoosException.ERROR405);
        default:
            throw new TopoosException("Error: " + rp.getStatusLine().getStatusCode() + "");
        }

    }
}

From source file:com.frank.search.solr.server.support.SolrClientUtils.java

private static HttpClient cloneHttpClient(HttpClient sourceClient) throws InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    if (sourceClient == null) {
        return null;
    }/*from  w w w . ja v  a  2  s.  c  o  m*/

    Class<?> clientType = ClassUtils.getUserClass(sourceClient);
    Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(clientType, HttpParams.class);
    if (constructor != null) {

        HttpClient targetClient = (HttpClient) constructor.newInstance(sourceClient.getParams());
        BeanUtils.copyProperties(sourceClient, targetClient);
        return targetClient;
    } else {
        return new DefaultHttpClient(sourceClient.getParams());
    }

}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

protected static HttpClient getHttpClient() {
    HttpClient httpClient = null;
    switch (clientType) {
    case CLIENT_WILDCARD:
        httpClient = getWildcartHttpClient(null);
        break;//from  w ww.  j  ava  2 s.c om
    case CLIENT_ACCEPTALL:
        httpClient = getAcceptAllHttpClient(null);
        break;
    default:
        httpClient = getDefaultHttpClient(null);
    }

    final HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS);
    return httpClient;
}

From source file:com.upyun.sdk.utils.HttpClientUtils.java

@SuppressWarnings("deprecation")
public static HttpClient getInstance() {
    HttpClient client = new DefaultHttpClient();
    SSLContext ctx = null;//from  w  ww .j a v  a 2  s.c o m
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { tm }, null);
    } catch (Exception e) {
        LogUtil.exception(logger, e);
    }
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = client.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    client = new DefaultHttpClient(ccm, client.getParams());
    return client;
}

From source file:com.bright.json.JSonRequestor.java

public static List<Cookie> doLogin(String user, String pass, String myURL) {
    try {//from w w w .  ja v  a 2s.  c  o  m
        cmLogin loginReq = new cmLogin("login", user, pass);

        GsonBuilder builder = new GsonBuilder();

        Gson g = builder.create();
        String json = g.toJson(loginReq);

        /* HttpClient httpclient = new DefaultHttpClient(); */

        HttpClient httpclient = getNewHttpClient();
        CookieStore cookieStore = new BasicCookieStore();

        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */

        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        HttpParams params = httpclient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 1000);
        HttpConnectionParams.setSoTimeout(params, 1000);
        HttpPost httppost = new HttpPost(myURL);
        StringEntity stringEntity = new StringEntity(json);
        stringEntity.setContentType("application/json");
        httppost.setEntity(stringEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost, localContext);

        System.out.println(response + "\n");
        for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) {
            System.out.println("\n Cookie: " + c.toString() + "\n");
        }

        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println("Chunked?: " + resEntity.isChunked());
            String message = new String(EntityUtils.toString(resEntity));
            System.out.println(message);
            return cookies;
        }
        EntityUtils.consume(resEntity);

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return null;

}

From source file:com.evrythng.java.wrapper.core.api.ApiCommand.java

private static HttpClient wrapClient(final HttpClient base) {

    try {//  w  ww.  ja v a2 s  . c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory ssf = new WrapperSSLSocketFactory(trustStore);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}