Example usage for org.apache.http.impl.client DefaultHttpClient execute

List of usage examples for org.apache.http.impl.client DefaultHttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient execute.

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.mimo.service.api.MimoHttpConnection.java

/**
 * Function for Making HTTP "get" request and getting server response.
 * //w  w w .ja  va 2  s  . co m
 * @param p_url
 *            - Http Url
 * @throws ClientProtocolException
 * @throws IOException
 * @return HttpResponse- Returns the HttpResponse.
 */
public static synchronized HttpResponse getHttpUrlConnection(String p_url)
        throws ClientProtocolException, IOException // throws
// CustomException
{

    DefaultHttpClient m_httpClient = new DefaultHttpClient();
    HttpGet m_get = new HttpGet(p_url);

    String m_authString = MimoAPIConstants.USERNAME + ":" + MimoAPIConstants.PASSWORD;
    String m_authStringEnc = Base64.encodeToString(m_authString.getBytes(), Base64.NO_WRAP);
    m_get.addHeader(MimoAPIConstants.HEADER_TEXT_AUTHORIZATION,
            MimoAPIConstants.HEADER_TEXT_BASIC + m_authStringEnc);
    HttpResponse m_response = null;

    try {
        m_response = m_httpClient.execute(m_get);
    } catch (IllegalStateException e) {
        if (MimoAPIConstants.DEBUG) {
            Log.e(TAG, e.getMessage());
        }
    }

    return m_response;
}

From source file:mobisocial.musubi.util.OGUtil.java

public static OGData getOrGuess(String url) {
    DefaultHttpClient hc = new DefaultHttpClient();
    HttpResponse res;//from   ww  w.ja  va2 s.c o  m
    try {
        HttpGet hg = new HttpGet(url);
        res = hc.execute(hg);
    } catch (Exception e) {
        Log.e(TAG, "unable to fetch page to get og tags", e);
        return null;
    }
    String location = url;
    //TODO: if some kind of redirect magic happened, then
    //make the location match that

    OGData og = new OGData();
    HttpEntity he = res.getEntity();
    Header content_type = he.getContentType();
    //TODO: check the content directly if they forget the type header
    if (content_type == null || content_type.getValue() == null) {
        Log.e(TAG, "page missing content type ..abandoning: " + url);
        return null;
    }
    og.mMimeType = content_type.getValue();
    //just make a thumbnail if the shared item is an image
    if (og.mMimeType.startsWith("image/")) {
        Bitmap b;
        try {
            b = BitmapFactory.decodeStream(he.getContent());
        } catch (Exception e) {
            return null;
        }
        //TODO: scaling
        int w = b.getWidth();
        int h = b.getHeight();
        if (w > h) {
            h = h * 200 / w;
            w = 200;
        } else {
            w = w * 200 / h;
            h = 200;
        }

        Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true);
        b.recycle();
        b = b2;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        b.compress(CompressFormat.PNG, 100, baos);
        og.mImage = baos.toByteArray();
        b.recycle();
        return og;
    }
    //if its not html, we can't extract more details, the caller
    //should rely on what they already know.
    if (!og.mMimeType.startsWith("text/html") && !og.mMimeType.startsWith("application/xhtml")) {
        Log.e(TAG, "shared content is not a known type for meta data processing " + og.mMimeType);
        return og;
    }

    String html;
    try {
        html = IOUtils.toString(he.getContent());
    } catch (Exception e) {
        Log.e(TAG, "failed to read html content", e);
        return og;
    }

    Matcher m = sTitleRegex.matcher(html);
    if (m.find()) {
        og.mTitle = StringEscapeUtils.unescapeHtml4(m.group(1));

    }
    m = sMetaRegex.matcher(html);
    int offset = 0;
    String raw_description = null;
    while (m.find(offset)) {
        try {
            String meta_tag = m.group();
            Matcher mp = sPropertyOfMeta.matcher(meta_tag);
            if (!mp.find())
                continue;
            String type = mp.group(1);
            type = type.substring(1, type.length() - 1);
            Matcher md = sContentOfMeta.matcher(meta_tag);
            if (!md.find())
                continue;
            String data = md.group(1);
            //remove quotes
            data = data.substring(1, data.length() - 1);
            data = StringEscapeUtils.unescapeHtml4(data);
            if (type.equalsIgnoreCase("og:title")) {
                og.mTitle = data;
            } else if (type.equalsIgnoreCase("og:image")) {
                HttpResponse resi;
                try {
                    HttpGet hgi = new HttpGet(data);
                    resi = hc.execute(hgi);
                } catch (Exception e) {
                    Log.e(TAG, "unable to fetch og image url", e);
                    continue;
                }
                HttpEntity hei = resi.getEntity();
                if (!hei.getContentType().getValue().startsWith("image/")) {
                    Log.e(TAG, "image og tag points to non image data" + hei.getContentType().getValue());
                }
                try {
                    Bitmap b;
                    try {
                        b = BitmapFactory.decodeStream(hei.getContent());
                    } catch (Exception e) {
                        return null;
                    }
                    //TODO: scaling
                    int w = b.getWidth();
                    int h = b.getHeight();
                    if (w > h) {
                        h = h * Math.min(200, w) / w;
                        w = Math.min(200, w);
                    } else {
                        w = w * Math.min(200, h) / h;
                        h = Math.min(200, h);
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true);
                    b.recycle();
                    b = b2;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    b.compress(CompressFormat.PNG, 100, baos);
                    b.recycle();
                    og.mImage = baos.toByteArray();
                } catch (Exception e) {
                    Log.e(TAG, "failed to fetch image for og", e);
                    continue;
                }
            } else if (type.equalsIgnoreCase("description")) {
                raw_description = data;
            } else if (type.equalsIgnoreCase("og:description")) {
                og.mDescription = data;
            } else if (type.equalsIgnoreCase("og:url")) {
                og.mUrl = data;
            }
        } finally {
            offset = m.end();
        }
    }
    HashSet<String> already_fetched = new HashSet<String>();
    if (og.mImage == null) {
        int max_area = 0;
        m = sImageRegex.matcher(html);
        int img_offset = 0;
        while (m.find(img_offset)) {
            try {
                String img_tag = m.group();
                Matcher ms = sSrcOfImage.matcher(img_tag);
                if (!ms.find())
                    continue;
                String img_src = ms.group(1);
                img_src = img_src.substring(1, img_src.length() - 1);
                img_src = StringEscapeUtils.unescapeHtml4(img_src);
                //don't fetch an image twice (like little 1x1 images)
                if (already_fetched.contains(img_src))
                    continue;
                already_fetched.add(img_src);
                HttpResponse resi;
                try {
                    HttpGet hgi = new HttpGet(new URL(new URL(location), img_src).toString());
                    resi = hc.execute(hgi);
                } catch (Exception e) {
                    Log.e(TAG, "unable to fetch image url for biggest image search" + img_src, e);
                    continue;
                }
                HttpEntity hei = resi.getEntity();
                if (hei == null) {
                    Log.w(TAG, "image missing en ..trying entity response: " + url);
                    continue;
                }
                Header content_type_image = hei.getContentType();
                if (content_type_image == null || content_type_image.getValue() == null) {
                    Log.w(TAG, "image missing content type ..trying anyway: " + url);
                }
                if (!content_type_image.getValue().startsWith("image/")) {
                    Log.w(TAG, "image tag points to non image data " + hei.getContentType().getValue() + " "
                            + img_src);
                }
                try {
                    Bitmap b;
                    try {
                        b = BitmapFactory.decodeStream(hei.getContent());
                    } catch (Exception e) {
                        return null;
                    }
                    //TODO: scaling
                    int w = b.getWidth();
                    int h = b.getHeight();
                    if (w * h <= max_area) {
                        continue;
                    }
                    if (w < 32 || h < 32) {
                        //skip dinky crap
                        continue;
                    }
                    if (w > h) {
                        h = h * Math.min(200, w) / w;
                        w = Math.min(200, w);
                    } else {
                        w = w * Math.min(200, h) / h;
                        h = Math.min(200, h);
                    }
                    Bitmap b2 = Bitmap.createScaledBitmap(b, w, h, true);
                    b.recycle();
                    b = b2;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    b.compress(CompressFormat.PNG, 100, baos);
                    og.mImage = baos.toByteArray();
                    b.recycle();
                    max_area = w * h;
                } catch (Exception e) {
                    Log.e(TAG, "failed to fetch image for og", e);
                    continue;
                }
            } finally {
                img_offset = m.end();
            }
        }

    }
    if (og.mDescription == null)
        og.mDescription = raw_description;
    return og;
}

From source file:org.bibalex.gallery.storage.BAGStorage.java

protected static List<String> listChildrenApacheHttpd(String dirUrlStr, FileType childrenType,
        DefaultHttpClient httpclient) throws BAGException {
    ArrayList<String> result = new ArrayList<String>();

    HttpGet httpReq = new HttpGet(dirUrlStr);
    try {/*from   www  .  j  av a  2s. c o  m*/

        HttpResponse response = httpclient.execute(httpReq);

        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            throw new BAGException("Connection error: " + response.getStatusLine().toString());
        }

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if ((entity != null)) {

            entity = new BufferedHttpEntity(entity);

            if (entity.getContentType().getValue().startsWith("text/html")) {
                SAXBuilder saxBuilder = new SAXBuilder();

                saxBuilder.setFeature("http://xml.org/sax/features/validation", false);
                saxBuilder.setFeature("http://xml.org/sax/features/namespaces", true);
                saxBuilder.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

                String htmlresponse = EntityUtils.toString(entity);
                String xmlResponse = light_html2xml.Html2Xml(htmlresponse);

                Document doc = saxBuilder.build(new StringReader(xmlResponse));
                XPath hrefXP = XPath.newInstance("//a/@href");

                for (Object obj : hrefXP.selectNodes(doc)) {
                    Attribute attr = (Attribute) obj;
                    String name = attr.getValue();
                    if (name.startsWith("/")) {
                        // parent dir
                        continue;
                    } else if (name.endsWith("/")) {
                        if (childrenType.equals(FileType.FOLDER)
                                || childrenType.equals(FileType.FILE_OR_FOLDER)) {
                            result.add(name.substring(0, name.length() - 1));
                        }
                    } else {
                        if (childrenType.equals(FileType.FILE)
                                || childrenType.equals(FileType.FILE_OR_FOLDER)) {
                            result.add(name);
                        }
                    }
                }
            }
        }

        return result;

    } catch (IOException ex) {

        // In case of an IOException the connection will be released
        // back to the connection manager automatically
        throw new BAGException(ex);

    } catch (RuntimeException ex) {

        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        httpReq.abort();
        throw ex;

    } catch (JDOMException e) {
        throw new BAGException(e);
    } finally {
        // connection closing is left for the caller to reuse connections

    }

}

From source file:com.mimo.service.api.MimoHttpConnection.java

/**
 * Function for Making HTTP "post" request and getting server response.
 * //from  w w w.  j ava 2  s  .  c  om
 * @param p_url
 *            - Http Url
 * @throws ClientProtocolException
 * @throws IOException
 * @return HttpResponse- Returns the HttpResponse.
 */
public static synchronized HttpResponse getHttpTransferUrlConnection(String p_url)
        throws ClientProtocolException, IOException // throws
// CustomException
{

    DefaultHttpClient m_httpClient = new DefaultHttpClient();
    HttpPost m_post = new HttpPost(p_url);

    String m_authString = MimoAPIConstants.USERNAME + ":" + MimoAPIConstants.PASSWORD;
    String m_authStringEnc = Base64.encodeToString(m_authString.getBytes(), Base64.NO_WRAP);
    m_post.addHeader(MimoAPIConstants.HEADER_TEXT_AUTHORIZATION,
            MimoAPIConstants.HEADER_TEXT_BASIC + m_authStringEnc);
    HttpResponse m_response = null;

    try {
        m_response = m_httpClient.execute(m_post);
    } catch (IllegalStateException e) {
        if (MimoAPIConstants.DEBUG) {
            Log.e(TAG, e.getMessage());
        }
    }

    return m_response;
}

From source file:com.sampullara.findmyiphone.FindMyDevice.java

private static void writeDeviceLocations(Writer out, String username, String password) throws IOException {
    // Initialize the HTTP client
    DefaultHttpClient hc = new DefaultHttpClient();

    // Authorize with Apple's mobile me service
    HttpGet auth = new HttpGet(
            "https://auth.apple.com/authenticate?service=DockStatus&realm=primary-me&formID=loginForm&username="
                    + username + "&password=" + password
                    + "&returnURL=aHR0cHM6Ly9zZWN1cmUubWUuY29tL3dvL1dlYk9iamVjdHMvRG9ja1N0YXR1cy53b2Evd2EvdHJhbXBvbGluZT9kZXN0aW5hdGlvblVybD0vYWNjb3VudA%3D%3D");
    hc.execute(auth);
    auth.abort();//from   w w  w.  j  a  v  a 2 s.c om

    // Pull the isc-secure.me.com cookie out so we can set the X-Mobileme-Isc header properly
    String isc = extractIscCode(hc);

    // Get access to the devices and find out their ids
    HttpPost devicemgmt = new HttpPost("https://secure.me.com/wo/WebObjects/DeviceMgmt.woa/?lang=en");
    devicemgmt.addHeader("X-Mobileme-Version", "1.0");
    devicemgmt.addHeader("X-Mobileme-Isc", isc);
    devicemgmt.setEntity(new UrlEncodedFormEntity(new ArrayList<NameValuePair>()));
    HttpResponse devicePage = hc.execute(devicemgmt);

    // Extract the device ids from their html encoded in json
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    devicePage.getEntity().writeTo(os);
    os.close();
    Matcher m = Pattern.compile("DeviceMgmt.deviceIdMap\\['[0-9]+'\\] = '([a-z0-9]+)';")
            .matcher(new String(os.toByteArray()));
    List<String> deviceList = new ArrayList<String>();
    while (m.find()) {
        deviceList.add(m.group(1));
    }

    // For each available device, get the location
    JsonFactory jf = new JsonFactory();
    JsonGenerator jg = jf.createJsonGenerator(out);
    jg.writeStartObject();
    for (String device : deviceList) {
        HttpPost locate = new HttpPost(
                "https://secure.me.com/wo/WebObjects/DeviceMgmt.woa/wa/LocateAction/locateStatus");
        locate.addHeader("X-Mobileme-Version", "1.0");
        locate.addHeader("X-Mobileme-Isc", isc);
        locate.setEntity(new StringEntity(
                "postBody={\"deviceId\": \"" + device + "\", \"deviceOsVersion\": \"7A341\"}"));
        locate.setHeader("Content-type", "application/json");
        HttpResponse location = hc.execute(locate);
        InputStream inputStream = location.getEntity().getContent();
        JsonParser jp = jf.createJsonParser(inputStream);
        jp.nextToken(); // ugly
        jg.writeFieldName(device);
        jg.copyCurrentStructure(jp);
        inputStream.close();
    }
    jg.close();
    out.close();
}

From source file:co.cask.cdap.gateway.handlers.ProcedureHandlerTest.java

private static void testTestServer() throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost request = new HttpPost(String
            .format("http://%s:%d/v2/apps/testApp1/procedures/testProc1/methods/testMethod1", hostname, port));
    HttpResponse response = httpclient.execute(request);
    Assert.assertEquals(HttpResponseStatus.OK.getCode(), response.getStatusLine().getStatusCode());
}

From source file:com.ocp.media.UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,
        ClientConnectionManager connectionManager) {
    InputStream contentInput = null;
    if (connectionManager == null) {
        try {//w ww . ja v  a2s  .  c om
            URL url = new URI(uri).toURL();
            URLConnection conn = url.openConnection();
            conn.connect();
            contentInput = conn.getInputStream();
        } catch (Exception e) {
            Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + uri);
            e.printStackTrace();
            return null;
        }
    } else {
        // We create a cancelable http request from the client
        final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
        HttpUriRequest request = new HttpGet(uri);
        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                // Wrap the entity input stream in a GZIP decoder if
                // necessary.
                contentInput = entity.getContent();
            }
        } catch (Exception e) {
            Log.w(Gallery.TAG, TAG + ": " + "Request failed: " + request.getURI());
            return null;
        }
    }
    if (contentInput != null) {
        return new BufferedInputStream(contentInput, 4096);
    } else {
        return null;
    }
}

From source file:com.cooliris.media.UriTexture.java

private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri,
        ClientConnectionManager connectionManager) {
    InputStream contentInput = null;
    if (connectionManager == null) {
        try {/* w ww  .j  av a 2  s.co  m*/
            URL url = new URI(uri).toURL();
            URLConnection conn = url.openConnection();
            conn.connect();
            contentInput = conn.getInputStream();
        } catch (Exception e) {
            Log.w(TAG, "Request failed: " + uri);
            e.printStackTrace();
            return null;
        }
    } else {
        // We create a cancelable http request from the client
        final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS);
        HttpUriRequest request = new HttpGet(uri);
        // Execute the HTTP request.
        HttpResponse httpResponse = null;
        try {
            httpResponse = mHttpClient.execute(request);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                // Wrap the entity input stream in a GZIP decoder if
                // necessary.
                contentInput = entity.getContent();
            }
        } catch (Exception e) {
            Log.w(TAG, "Request failed: " + request.getURI());
            return null;
        }
    }
    if (contentInput != null) {
        return new BufferedInputStream(contentInput, 4096);
    } else {
        return null;
    }
}

From source file:net.homelinux.penecoptero.android.citybikes.app.RESTHelper.java

public static final String restGET(String url, boolean authenticated, String username, String password)
        throws ClientProtocolException, IOException, HttpException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (authenticated) {
        httpclient = setCredentials(httpclient, url, username, password);
    }//from ww  w  .j a v a  2  s .  c o  m
    // Prepare a request object
    HttpGet httpmethod = new HttpGet(url);

    // Execute the request
    HttpResponse response;

    String result = null;

    try {
        response = httpclient.execute(httpmethod);
        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        // to worry about connection release

        if (entity != null) {
            InputStream instream = entity.getContent();
            result = convertStreamToString(instream);
            instream.close();
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return result;
}

From source file:com.lvwallpapers.utils.WebServiceUtils.java

public static List<UserGallery> getGalleries(String categoryName) {
    List<UserGallery> lstGallerys = new ArrayList<UserGallery>();

    try {// ww  w .  j  a  v  a 2  s  .c  om

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(getWebUrlGalleries());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String result = EntityUtils.toString(httpEntity);
        Log.e("Message", result);
        if (result != null && result.length() > 0) {
            JSONObject jobject = new JSONObject(result);
            String jsonPhotos = jobject.getString("galleries");

            JSONObject joPhotos = new JSONObject(jsonPhotos);

            String photos = joPhotos.getString("gallery");

            JSONArray joarray = new JSONArray(photos);

            for (int i = 0; i < joarray.length(); i++) {
                JSONObject jo = joarray.getJSONObject(i);
                String id = jo.getString("id");
                String title = jo.getString("title");
                JSONObject joTitle = new JSONObject(title);
                String content = joTitle.getString("_content");

                if (content.startsWith(categoryName)) {
                    UserGallery userGallery = new UserGallery(id, content);
                    lstGallerys.add(userGallery);
                }
            }

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

    }

    return lstGallerys;

}