Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

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

Prototype

BasicResponseHandler

Source Link

Usage

From source file:com.adam.aslfms.service.NPNotifier.java

/**
 * Connects to Last.fm servers and requests a Now Playing notification of
 * <code>track</code>. If an error occurs, exceptions are thrown.
 * //from   w w  w .j a  v  a 2s.  c om
 * @param track
 *            the track to send as notification
 * @throws BadSessionException
 *             means that a new handshake is needed
 * @throws TemporaryFailureException
 * @throws UnknownResponseException
 *             {@link UnknownResponseException}
 * 
 */
public void notifyNowPlaying(Track track, HandshakeResult hInfo)
        throws BadSessionException, TemporaryFailureException {
    Log.d(TAG, "Notifying now playing: " + getNetApp().getName());

    Log.d(TAG, getNetApp().getName() + ": " + track.toString());

    DefaultHttpClient http = new DefaultHttpClient();
    HttpPost request = new HttpPost(hInfo.nowPlayingUri);

    List<BasicNameValuePair> data = new LinkedList<BasicNameValuePair>();

    data.add(new BasicNameValuePair("s", hInfo.sessionId));
    data.add(new BasicNameValuePair("a", track.getArtist()));
    data.add(new BasicNameValuePair("b", track.getAlbum()));
    data.add(new BasicNameValuePair("t", track.getTrack()));
    data.add(new BasicNameValuePair("l", Integer.toString(track.getDuration())));
    data.add(new BasicNameValuePair("n", track.getTrackNr()));
    data.add(new BasicNameValuePair("m", track.getMbid()));

    try {
        request.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));
        ResponseHandler<String> handler = new BasicResponseHandler();
        String response = http.execute(request, handler);
        if (response.startsWith("OK")) {
            Log.i(TAG, "Nowplaying success: " + getNetApp().getName());
        } else if (response.startsWith("BADSESSION")) {
            throw new BadSessionException("Nowplaying failed because of badsession");
        } else {
            throw new TemporaryFailureException("NowPlaying failed weirdly: " + response);
        }

    } catch (ClientProtocolException e) {
        throw new TemporaryFailureException(TAG + ": " + e.getMessage());
    } catch (IOException e) {
        throw new TemporaryFailureException(TAG + ": " + e.getMessage());
    } finally {
        http.getConnectionManager().shutdown();
    }
}

From source file:com.moods_final.moods.entertainment.VideoListDemoActivity.java

public void getVideosData() {

    try {//w w  w  .  j  av  a2 s.  c o  m
        videos.clear();
        String searchUrl = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=20&playlistId="
                + pid + "&key=AIzaSyBHCABhIbvbpAknRONYBUyGdEBWSYawbLQ";
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(searchUrl);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String responseBody = null;

        responseBody = client.execute(get, responseHandler);
        Log.e("aaa", responseBody);

        JSONObject jsonObject = new JSONObject(responseBody);
        JSONObject j = null;
        JSONArray arr = jsonObject.getJSONArray("items");
        String title, id, snippet;

        //JSONArray photos
        for (int i = 0; i < arr.length(); i++) {
            j = new JSONObject(arr.getJSONObject(i).toString());

            snippet = j.getString("snippet");
            j = new JSONObject(snippet);
            title = j.getString("title");
            Log.e("mmm", "title=" + title);

            id = arr.getJSONObject(i).getJSONObject("snippet").getJSONObject("resourceId").getString("videoId");
            Log.e("mmm", "vid=" + id);

            //id= jsonObject.getJSONArray("response").getJSONObject(i).getString("blog_name");

            /*getJSONArray("photos")*/
            //arr = jsonObject.getJSONArray("response");
            //Log.e("aaa","\n\n"+arr.get(0).toString());

            /*Log.e("mmm", "blog name=" + blog);
            summary = arr.getJSONObject(i).getString("summary");
            url = arr.getJSONObject(i).getString("post_url");
            Log.e("mmm", "summary=" + summary + " ,url=" + url);
            //arr1 = arr.getJSONObject(i).getJSONArray("photos");
            //image = arr1.getJSONObject(0).getJSONArray("alt_sizes").getJSONObject(0).getString("url");
            // Log.e("mmm", "image=" + image);
            */videos.add(new ArrayList<String>());
            videos.get(i).add("" + title);
            videos.get(i).add("" + id);

        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.e("aaa", "JSONException");
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.fao.geonet.api.records.editing.InspireValidatorUtils.java

/**
 * Upload metadata file.//from w  w  w . ja v a 2  s . c o m
 *
 * @param endPoint the end point
 * @param xml the xml
 * @param client the client (optional)
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws JSONException the JSON exception
 */
private static String uploadMetadataFile(String endPoint, InputStream xml, CloseableHttpClient client)
        throws IOException, JSONException {

    boolean close = false;
    if (client == null) {
        client = HttpClients.createDefault();
        close = true;
    }

    try {

        HttpPost request = new HttpPost(endPoint + TestObjects_URL + "?action=upload");

        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept", ACCEPT);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("fileupload", xml, ContentType.TEXT_XML, "file.xml");
        HttpEntity entity = builder.build();

        request.setEntity(entity);

        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {

            ResponseHandler<String> handler = new BasicResponseHandler();
            String body = handler.handleResponse(response);
            JSONObject jsonRoot = new JSONObject(body);
            return jsonRoot.getJSONObject("testObject").getString("id");
        } else {
            Log.warning(Log.SERVICE, "WARNING: INSPIRE service HTTP response: "
                    + response.getStatusLine().getStatusCode() + " for " + TestObjects_URL);
            return null;
        }
    } catch (Exception e) {
        Log.error(Log.SERVICE, "Error calling INSPIRE service: " + endPoint, e);
        return null;
    } finally {
        if (close) {
            try {
                client.close();
            } catch (IOException e) {
                Log.error(Log.SERVICE, "Error closing CloseableHttpClient: " + endPoint, e);
            }
        }
    }
}

From source file:com.tlabs.eve.HttpClientTest.java

protected final String get(String url) {
    HttpClient httpclient = new DefaultHttpClient(connectionManager);
    try {//from   w  w  w.  j  a  v  a2s.c om
        HttpGet get = new HttpGet(url);
        return httpclient.execute(get, new BasicResponseHandler());
    } catch (Exception e) {
        e.printStackTrace(System.err);
        //fail(e.getLocalizedMessage());
        return null;
        //throw e;
    }
}

From source file:org.apache.activemq.transport.discovery.http.HTTPDiscoveryAgent.java

@SuppressWarnings("unused")
synchronized private void doUnRegister(String service) {
    String url = registryURL;/*from  w ww .  ja  v a2  s .c  om*/
    try {
        HttpDelete method = new HttpDelete(url);
        method.addHeader("service", service);
        ResponseHandler<String> handler = new BasicResponseHandler();
        String responseBody = httpClient.execute(method, handler);
        LOG.debug("DELETE to " + url + " got a " + responseBody);
    } catch (Exception e) {
        LOG.debug("DELETE to " + url + " failed with: " + e);
    }
}

From source file:uk.co.uwcs.choob.modules.HttpModule.java

/**
 * Constructor.
 *
 */
public HttpModule() {
    responseHandler = new BasicResponseHandler();
}

From source file:com.ubikod.urbantag.ContentViewerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle extras = getIntent().getExtras();

    /* If we are coming from Notification delete notification */
    if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_CONTENT_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closeContentNotif();
    } else if (extras.getInt(NotificationHelper.FROM_NOTIFICATION, -1) == NotificationHelper.NEW_PLACE_NOTIF) {
        NotificationHelper notificationHelper = new NotificationHelper(this);
        notificationHelper.closePlaceNotif();
    }//  ww w . j a  v a2  s  .co m

    /* Fetch content info */
    ContentManager contentManager = new ContentManager(new DatabaseHelper(this, null));
    Log.i(UrbanTag.TAG, "View content : " + extras.getInt(CONTENT_ID));
    this.content = contentManager.get(extras.getInt(CONTENT_ID));
    if (this.content == null) {
        Toast.makeText(this, R.string.error_occured, Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    setTitle(content.getName());
    com.actionbarsherlock.app.ActionBar actionBar = this.getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    setContentView(R.layout.content_viewer);

    /* Find webview and create url for content */
    final WebView webView = (WebView) findViewById(R.id.webview);
    final String URL = UrbanTag.API_URL + ACTION_GET_CONTENT.replaceAll("%", "" + this.content.getId());

    /* Display progress animation */
    final ProgressDialog progress = ProgressDialog.show(this, "",
            this.getResources().getString(R.string.loading_content), false, true,
            new DialogInterface.OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    timeOutHandler.interrupt();
                    webView.stopLoading();
                    ContentViewerActivity.this.finish();
                }

            });

    /* Go fetch content */
    contentFetcher = new Thread(new Runnable() {

        DefaultHttpClient httpClient;

        @Override
        public void run() {
            Looper.prepare();
            Log.i(UrbanTag.TAG, "Fetching content...");
            httpClient = new DefaultHttpClient();
            try {
                String responseBody = httpClient.execute(new HttpGet(URL), new BasicResponseHandler());
                webView.loadDataWithBaseURL("fake://url/for/encoding/hack...", responseBody, mimeType, encoding,
                        "");
                timeOutHandler.interrupt();
                if (progress.isShowing())
                    progress.dismiss();
            } catch (ClientProtocolException cpe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            } catch (IOException ioe) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                timeOutHandler.interrupt();
                progress.cancel();
            }

            Looper.loop();
        }

    });
    contentFetcher.start();

    /* TimeOut Handler */
    timeOutHandler = new Thread(new Runnable() {
        private int INCREMENT = 1000;

        @Override
        public void run() {
            Looper.prepare();
            try {
                for (int time = 0; time < TIMEOUT; time += INCREMENT) {
                    Thread.sleep(INCREMENT);
                }

                Log.w(UrbanTag.TAG, "TimeOut !");
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), R.string.error_loading_content,
                                Toast.LENGTH_SHORT).show();
                    }
                });

                contentFetcher.interrupt();
                progress.cancel();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            Looper.loop();

        }

    });
    timeOutHandler.start();

}

From source file:com.vishwa.pinit.LocationSuggestionProvider.java

private MatrixCursor getLocationSuggestionsUsingAPI(String query, MatrixCursor cursor) {
    String transformedQuery = query.replace(" ", "+");
    String queryUrl = mGoogleGeocodingEndpoint + transformedQuery + "&sensor=false";

    try {/*www. j  a v a  2  s  .  co m*/

        JSONObject apiResponse = new JSONObject(
                mAndroidHttpClient.execute(new HttpGet(queryUrl), new BasicResponseHandler()));
        JSONArray results = (JSONArray) apiResponse.get("results");

        for (int i = 0; i < results.length(); i++) {
            String formattedAddress;
            JSONObject result = results.getJSONObject(i);
            if (result.has("formatted_address")) {
                formattedAddress = result.getString("formatted_address");
                if (result.has("geometry")) {
                    JSONObject geometry = result.getJSONObject("geometry");
                    if (geometry.has("location")) {
                        JSONObject location = geometry.getJSONObject("location");
                        double latitude = location.getDouble("lat");
                        double longitude = location.getDouble("lng");
                        cursor.addRow(new String[] { Integer.toString(i), formattedAddress, "",
                                latitude + "," + longitude });
                    }
                }
            }
        }
        return cursor;
    } catch (ClientProtocolException e) {
        cursor.addRow(new String[] { "0", "Search is not available currently", "Try again later.", "" });
        return cursor;
    } catch (JSONException e) {
        cursor.addRow(new String[] { "0", "Search is not available currently", "Try again later.", "" });
        return cursor;
    } catch (IOException e) {
        cursor.addRow(new String[] { "0", "Search is not available currently", "Try again later.", "" });
        return cursor;
    }
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

/**
 * Sends HTTP GET request and returns body of response from server as String
 *//*from w  w w .  jav  a  2s. c o m*/
public String httpGet(final String urlToServer, final List<BasicNameValuePair> parameterList)
        throws IOException {
    final String url = urlToServer + "?" + URLEncodedUtils.format(parameterList, null);
    final HttpGet request = new HttpGet(url);
    final ResponseHandler<String> responseHandler = new BasicResponseHandler();
    final String responseBody = client.execute(request, responseHandler);
    return responseBody;
}

From source file:org.sociotech.communitymashup.source.languagedetection.apiwrapper.DetectLanguageAPIWrapper.java

private String doPost(String url, Map<String, String> parameterMap) {
    String result = null;/* w w w . j a va 2s .  c o m*/

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(url);

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

    // add all post parameter
    for (String key : parameterMap.keySet()) {
        nameValuePairs.add(new BasicNameValuePair(key, parameterMap.get(key)));
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    try {
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        result = httpClient.execute(post, responseHandler);
    } catch (Exception e) {
        // do nothing
    } finally {
        // client is no longer needed
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}