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:Main.java

public static String initializeService(String data, String serviceName, String serviceUrl) {
    Log.d("EliademyUtils", "initializeService");
    try {//  w w w .  j  a  va 2 s  .  c  o m
        JSONObject jsObj = new JSONObject(data.toString());
        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpPost httppost = new HttpPost(serviceUrl + "/login/token.php");

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("username", jsObj.get("username").toString()));
        nameValuePairs.add(new BasicNameValuePair("password", jsObj.get("password").toString()));
        nameValuePairs.add(new BasicNameValuePair("service", serviceName));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            StringBuilder jsonStr = new StringBuilder();
            InputStream iStream = entity.getContent();
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iStream));
            String jpart;
            while ((jpart = bufferReader.readLine()) != null) {
                jsonStr.append(jpart);
            }
            iStream.close();
            Log.d("Moodle", jsonStr.toString());
            JSONObject jsonObj = new JSONObject(jsonStr.toString());
            return (String) jsonObj.get("token");
        }
    } catch (Exception e) {
        Log.e("EliademyUtils", "exception", e);
        return null;
    }
    return null;
}

From source file:no.ntnu.wifimanager.ServerUtilities.java

public static JSONArray getJSONArray(String url, String userId) {

    InputStream is = null;/*from  w w w. j  a v a  2 s  . co m*/
    JSONArray jArray = null;
    String json = "";

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("user_id", userId));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;
}

From source file:com.lurencun.cfuture09.androidkit.http.Http.java

/**
 * HTTP URIString/*w ww . j ava  2 s . c  o m*/
 *
 * @param request
 *            HTTP URI
 * @return String
 * @throws IOException
 *             ??IO
 */
private static String sendRequest(HttpUriRequest request) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(request);
    return EntityUtils.toString(response.getEntity());
}

From source file:se.vgregion.util.HTTPUtils.java

public static HttpResponse makePostAttachments(String url, String token, DefaultHttpClient httpclient,
        Attachment attachment) throws Exception {

    HttpPost httppost = new HttpPost(url);
    httppost.addHeader("X-TrackerToken", token);
    httppost.removeHeaders("Connection");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody content = new SizedInputStreamBody(attachment.getData(), attachment.getFilename(),
            attachment.getFileLength());
    mpEntity.addPart("Filedata", content);
    httppost.setEntity(mpEntity);//  w  ww. java 2s.c o m

    return httpclient.execute(httppost);
}

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

public static GalleryM getGallery(int page) {

    GalleryM galleryM = new GalleryM();
    List<PhotoGallery> lstGalleryPhoto = new ArrayList<PhotoGallery>();

    try {//from  w ww. j a va2 s . co m

        Log.e("URL DSAHDKJA", getWeb_UrlGallery(page));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(getWeb_UrlGallery(page));
        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("photos");

            JSONObject joPhotos = new JSONObject(jsonPhotos);

            int pageG = joPhotos.getInt("page");
            int pages = joPhotos.getInt("pages");

            galleryM.page = pageG;
            galleryM.pages = pages;

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

            JSONArray joarray = new JSONArray(photos);

            for (int i = 0; i < joarray.length(); i++) {
                JSONObject jo = joarray.getJSONObject(i);

                PhotoGallery photo = new PhotoGallery();
                String id = jo.getString("id");
                String secret = jo.getString("secret");
                String server = jo.getString("server");
                String farm = jo.getString("farm");
                String url_m = (jo.has("url_m")) ? jo.getString("url_m") : "";
                String url_s = (jo.has("url_s")) ? jo.getString("url_s") : "";
                String url_o = (jo.has("url_o")) ? jo.getString("url_o") : "";
                String url_l = (jo.has("url_l")) ? jo.getString("url_l") : url_o;

                if (url_o.length() == 0 && url_l.length() == 0) {
                    url_l = url_s;
                }

                photo.photoId = id;
                photo.secret = secret;
                photo.server = server;
                photo.farm = farm;
                photo.url_l = url_l;
                photo.url_m = url_m;
                photo.url_s = url_s;

                lstGalleryPhoto.add(photo);
            }

            galleryM.lstPhotoGallery = lstGalleryPhoto;

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

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

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

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

    }

    return galleryM;

}

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

public static List<Category> getAllCategory() {
    List<Category> listCategory = new ArrayList<Category>();

    List<String> listContain = new ArrayList<>();

    try {//from  w  ww.jav a  2 s  .  co m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(getWebUrlGalleries());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        String result = EntityUtils.toString(httpEntity);

        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 = joarray.length() - 1; i >= 0; i--) {
                JSONObject jo = joarray.getJSONObject(i);

                String id = jo.getString("id");
                String title = jo.getString("title");
                String numOfPhotos = jo.getString("count_photos");
                int farm = jo.getInt("primary_photo_farm");
                String secret = jo.getString("primary_photo_secret");
                String server = jo.getString("primary_photo_server");
                String photoId = jo.getString("primary_photo_id");

                JSONObject joTitle = new JSONObject(title);
                String content = joTitle.getString("_content");

                StringTokenizer stringTokenizer = new StringTokenizer(content, "_");
                String categoryName = stringTokenizer.nextToken();
                String cateNo = stringTokenizer.nextToken();

                //

                if (!listContain.contains(categoryName)) {

                    listContain.add(categoryName);
                    Category category = new Category();
                    category.categoryName = categoryName;
                    if (cateNo.equalsIgnoreCase("0")) {
                        category.imageLink = "http://farm" + farm + ".staticflickr.com/" + server + "/"
                                + photoId + "_" + secret + "_b.jpg";

                    }
                    category.numOfPhotos = category.numOfPhotos + Integer.parseInt(numOfPhotos);

                    listCategory.add(category);

                } else {

                    for (int j = 0; j < listCategory.size(); j++) {
                        if (listCategory.get(j).categoryName.equalsIgnoreCase(categoryName)) {
                            if (cateNo.equalsIgnoreCase("0")) {
                                listCategory.get(j).imageLink = "http://farm" + farm + ".staticflickr.com/"
                                        + server + "/" + photoId + "_" + secret + "_b.jpg";
                            }
                            listCategory.get(j).numOfPhotos = listCategory.get(j).numOfPhotos
                                    + Integer.parseInt(numOfPhotos);
                            break;
                        }
                    }
                }

            }

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

    }

    return listCategory;

}

From source file:com.dajodi.scandic.ScandicSessionHelper.java

public static InputStream get(URI uri) {

    DefaultHttpClient client = Singleton.INSTANCE.getHttpClient();
    try {// w w w  . jav  a2s .com

        HttpGet get = new HttpGet(uri);

        Util.gzipify(get);

        final HttpParams params = new BasicHttpParams();
        HttpClientParams.setRedirecting(params, false);
        get.setParams(params);

        Log.d("Executing get");

        // should give us a 302
        HttpResponse response = client.execute(get);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ScandicHtmlException("Expected a 200, got " + response.getStatusLine());
        }

        InputStream instream = Util.ungzip(response);
        return instream;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }
}

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

public static GalleryM getGallery(String galleryId) {

    GalleryM galleryM = new GalleryM();
    List<PhotoGallery> lstGalleryPhoto = new ArrayList<PhotoGallery>();

    try {/*from ww w. j  a  va  2s.  co  m*/

        Log.e("URL DSAHDKJA", getWeb_UrlGallery(galleryId));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(getWeb_UrlGallery(galleryId));
        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("photos");

            JSONObject joPhotos = new JSONObject(jsonPhotos);

            int pageG = joPhotos.getInt("page");
            int pages = joPhotos.getInt("pages");

            galleryM.page = pageG;
            galleryM.pages = pages;

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

            JSONArray joarray = new JSONArray(photos);

            for (int i = 0; i < joarray.length(); i++) {
                JSONObject jo = joarray.getJSONObject(i);

                PhotoGallery photo = new PhotoGallery();
                String id = jo.getString("id");
                String secret = jo.getString("secret");
                String server = jo.getString("server");
                String imgName = jo.getString("title");
                String farm = jo.getString("farm");
                String url_m = (jo.has("url_m")) ? jo.getString("url_m") : "";
                String url_s = (jo.has("url_s")) ? jo.getString("url_s") : "";
                String url_o = (jo.has("url_o")) ? jo.getString("url_o") : "";
                String url_h = (jo.has("url_h")) ? jo.getString("url_h") : "";
                String url_k = (jo.has("url_k")) ? jo.getString("url_k") : "";
                String url_l = (jo.has("url_l")) ? jo.getString("url_l") : "";

                if (url_l.length() == 0) {
                    url_l = url_m;
                }

                photo.photoId = id;
                photo.photoName = imgName;
                photo.secret = secret;
                photo.server = server;
                photo.farm = farm;
                photo.url_l = url_l;
                photo.url_m = url_m;
                photo.url_s = url_s;
                photo.url_o = url_o;
                photo.url_h = url_h;
                photo.url_k = url_k;

                lstGalleryPhoto.add(photo);
            }

            galleryM.lstPhotoGallery = lstGalleryPhoto;

        }
    } catch (Exception e) {

    }

    return galleryM;

}

From source file:com.onemorecastle.util.HttpFetch.java

public static Bitmap fetchBitmap(String imageAddress, int sampleSize)
        throws MalformedURLException, IOException {
    Bitmap bitmap = null;/*from   w w  w  .  ja  va2 s .co  m*/
    DefaultHttpClient httpclient = null;
    try {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        HttpConnectionParams.setSocketBufferSize(httpParameters, 512);
        HttpGet httpRequest = new HttpGet(URI.create(imageAddress));
        httpclient = new DefaultHttpClient();
        httpclient.setParams(httpParameters);
        HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
        InputStream instream = bufHttpEntity.getContent();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //first decode with inJustDecodeBounds=true to check dimensions
        options.inJustDecodeBounds = true;
        options.inSampleSize = sampleSize;
        BitmapFactory.decodeStream(instream, null, options);
        //decode bitmap with inSampleSize set
        options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inDither = true;
        options.inJustDecodeBounds = false;
        //response=(HttpResponse)httpclient.execute(httpRequest);
        //entity=response.getEntity();
        //bufHttpEntity=new BufferedHttpEntity(entity);
        instream = bufHttpEntity.getContent();
        bitmap = BitmapFactory.decodeStream(instream, null, options);
        //close out stuff
        try {
            instream.close();
            bufHttpEntity.consumeContent();
            entity.consumeContent();
        } finally {
            instream = null;
            bufHttpEntity = null;
            entity = null;
        }
    } catch (Exception x) {
        Log.e("HttpFetch.fetchBitmap", imageAddress, x);
    } finally {
        httpclient = null;
    }
    return (bitmap);
}

From source file:com.TaxiDriver.jy.DriverQuery.java

public static List<String> getPrefList(String s) {

    HttpPost postJob = new HttpPost(HttpHelper.domain + "getPrefOptions.php");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 4900;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    DefaultHttpClient clientJob = new DefaultHttpClient(httpParameters);

    try {/*from   w  w  w. j  av a 2s  .  co m*/
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("msgtype", s));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));
        HttpResponse response = clientJob.execute(postJob);

        String jsonString = HttpHelper.request(response);
        JSONArray jArray = new JSONArray(jsonString);

        List<String> list = new ArrayList<String>();
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json = jArray.getJSONObject(i);
            list.add(json.getString(s));
        }
        return list;

    } catch (Exception ex) {
        return null;

    }

}