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:org.androidnerds.reader.util.api.Authentication.java

/**
 * This method generates a quick token to send with API requests that require
 * editing content. This method is called as the API request is being built so
 * that it doesn't expire prior to the actual execution.
 *
 * @param sid - the user's authentication token from ClientLogin
 * @return token - the edit token generated by the server.
 *
 *//*from   w  w  w .  j av  a 2s .c o m*/
public static String generateFastToken(String sid) {
    try {
        BasicClientCookie cookie = Authentication.buildCookie(sid);
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCookieStore().addCookie(cookie);

        HttpGet get = new HttpGet(TOKEN_URL);
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();

        Log.d(TAG, "Server Response: " + response.getStatusLine());

        InputStream in = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;

        while ((line = reader.readLine()) != null) {
            Log.d(TAG, "Response Content: " + line);
        }

        reader.close();
        client.getConnectionManager().shutdown();

        return line;
    } catch (Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}

From source file:Main.java

public static HttpResponse postJson(String path, ArrayList<NameValuePair> params) throws Exception {

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(path);
    httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    httpPost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    httpPost.setHeader("X-Requested-With", "XMLHttpRequest");

    return httpClient.execute(httpPost);
}

From source file:de.incoherent.suseconferenceclient.app.HTTPWrapper.java

public static JSONObject get(String url) throws IllegalStateException, SocketException,
        UnsupportedEncodingException, IOException, JSONException {
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme("https", socketFactory, 443));
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
    DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    HttpGet get = new HttpGet(url);
    HttpResponse response = httpClient.execute(get);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode >= 200 && statusCode <= 299) {
        return HTTPWrapper.parseResponse(response);
    } else {//  w ww .  j  a va2  s  . c om
        throw new HttpResponseException(statusCode, statusLine.getReasonPhrase());
    }
}

From source file:net.line2soft.preambul.utils.Network.java

/**
 * Downloads a file from the Internet//from  ww w .j a  v  a 2  s  .c  o  m
 * @param address The URL of the file
 * @param dest The destination directory
 * @return The queried file
 * @throws IOException HTTP connection error, or writing error
 */
public static File download(URL address, File dest) throws IOException {
    File result = null;
    InputStream in = null;
    BufferedOutputStream out = null;
    //Open streams
    try {
        HttpGet httpGet = new HttpGet(address.toExternalForm());
        HttpParams httpParameters = new BasicHttpParams();
        // Set the timeout in milliseconds until a connection is established.
        int timeoutConnection = 4000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT)
        int timeoutSocket = 5000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        httpClient.setParams(httpParameters);
        HttpResponse response = httpClient.execute(httpGet);

        //Launch streams for download
        in = new BufferedInputStream(response.getEntity().getContent());
        String filename = address.getFile().substring(address.getFile().lastIndexOf("/") + 1);
        File tmp = new File(dest.getPath() + File.separator + filename);
        out = new BufferedOutputStream(new FileOutputStream(tmp));

        //Test if connection is OK
        if (response.getStatusLine().getStatusCode() / 100 == 2) {
            //Download and write
            try {
                int byteRead = in.read();
                while (byteRead >= 0) {
                    out.write(byteRead);
                    byteRead = in.read();
                }
                result = tmp;
            } catch (IOException e) {
                throw new IOException("Error while writing file: " + e.getMessage());
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Error while downloading: " + e.getMessage());
    } finally {
        //Close streams
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
    }
    return result;
}

From source file:no.uib.tools.OnthologyHttpClient.java

private static BufferedReader getContentBufferedReader(String uri) {
    try {/*from  ww  w.j av  a 2  s .c o  m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(uri);
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed to quety the PSIMOD onthology : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        httpClient.getConnectionManager().shutdown();

        return br;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:jp.co.conit.sss.sp.ex1.util.HttpUtil.java

/**
 * POST??????//from w  w w.  ja  v  a 2  s  .c o  m
 * 
 * @param url API?URL
 * @param httpEntity ?
 * @return
 */
public static String post(String url, UrlEncodedFormEntity httpEntity) throws Exception {

    if (url == null) {
        throw new IllegalArgumentException("'url' must not be null.");
    }
    if (httpEntity == null) {
        throw new IllegalArgumentException("'httpEntity' must not be null.");
    }

    String result = null;

    DefaultHttpClient httpclient = new DefaultHttpClient(getHttpParam());
    HttpPost httpPost = new HttpPost(url);

    try {
        httpPost.setEntity(httpEntity);
        HttpResponse response = httpclient.execute(httpPost);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        response.getEntity().writeTo(byteArrayOutputStream);
        result = byteArrayOutputStream.toString();
    } catch (ClientProtocolException e) {
        throw new Exception();
    } catch (IllegalStateException e) {
        throw new Exception();
    } catch (IOException e) {
        throw new Exception();
    }

    return result;
}

From source file:com.quietlycoding.android.reader.util.api.Authentication.java

/**
 * This method generates a quick token to send with API requests that
 * require editing content. This method is called as the API request is
 * being built so that it doesn't expire prior to the actual execution.
 * /*from   w w  w.j  a v  a 2s  .  c o  m*/
 * @param sid
 *            - the user's authentication token from ClientLogin
 * @return token - the edit token generated by the server.
 * 
 */
public static String generateFastToken(String sid) {
    try {
        final BasicClientCookie cookie = Authentication.buildCookie(sid);
        final DefaultHttpClient client = new DefaultHttpClient();

        client.getCookieStore().addCookie(cookie);

        final HttpGet get = new HttpGet(TOKEN_URL);
        final HttpResponse response = client.execute(get);
        final HttpEntity entity = response.getEntity();

        Log.d(TAG, "Server Response: " + response.getStatusLine());

        final InputStream in = entity.getContent();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;

        while ((line = reader.readLine()) != null) {
            Log.d(TAG, "Response Content: " + line);
        }

        reader.close();
        client.getConnectionManager().shutdown();

        return line;
    } catch (final Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}

From source file:org.broadinstitute.gatk.utils.help.ForumAPIUtils.java

private static String httpGet(String urlStr) {
    String output = "";

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

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(urlStr);
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        output = IOUtils.toString(response.getEntity().getContent());

        httpClient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();
    }
    return output;
}

From source file:org.androidnerds.reader.util.api.Subscriptions.java

/**
 * This method queries Google Reader for the list of subscribed feeds.
 * //from   w  ww  . j  a va  2 s  .  com
 * @param sid authentication code to pass along in a cookie.
 * @return arr returns a JSONArray of JSONObjects for each feed.
 *
 * The JSONObject returned by the service looks like this:
 *    id: this is the feed url.
 *    title: this is the title of the feed.
 *    sortid: this has not been figured out yet.
 *    firstitemsec: this has not been figured out yet.
 */
public static JSONArray getSubscriptionList(String sid) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(SUB_URL + "/list?output=json");
    BasicClientCookie cookie = Authentication.buildCookie(sid);

    try {
        client.getCookieStore().addCookie(cookie);

        HttpResponse response = client.execute(get);
        HttpEntity respEntity = response.getEntity();

        Log.d(TAG, "Response from server: " + response.getStatusLine());

        InputStream in = respEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line = "";
        String arr = "";
        while ((line = reader.readLine()) != null) {
            arr += line;
        }

        JSONObject obj = new JSONObject(arr);
        JSONArray array = obj.getJSONArray("subscriptions");

        reader.close();
        client.getConnectionManager().shutdown();

        return array;
    } catch (Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}

From source file:org.androidnerds.reader.util.api.Tags.java

/**
 * This method pulls the tags from Google Reader, its used by the 
 * methods in this class to communicate before parsing the specific
 * results./*from ww w .  j  a  v  a 2  s  .  c  o m*/
 *
 * @param sid the Google Reader authentication string.
 * @return arr JSONArray of the items from the server.
 */
private static JSONArray pullTags(String sid) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(URL);
    BasicClientCookie cookie = Authentication.buildCookie(sid);

    try {
        client.getCookieStore().addCookie(cookie);

        HttpResponse response = client.execute(get);
        HttpEntity respEntity = response.getEntity();

        Log.d(TAG, "Response from server: " + response.getStatusLine());

        InputStream in = respEntity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line = "";
        String arr = "";
        while ((line = reader.readLine()) != null) {
            arr += line;
        }

        JSONObject obj = new JSONObject(arr);
        JSONArray array = obj.getJSONArray("tags");

        return array;
    } catch (Exception e) {
        Log.d(TAG, "Exception caught:: " + e.toString());
        return null;
    }
}