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

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

Introduction

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

Prototype

public DefaultHttpClient() 

Source Link

Usage

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

/**
 * This method queries Google Reader for the list of subscribed feeds.
 * /* w  w w  .  j  a  va 2s.c om*/
 * @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:fitmon.WorkoutApi.java

public StringBuilder apiGetInfo()
        throws ClientProtocolException, IOException, NoSuchAlgorithmException, InvalidKeyException {
    HttpClient client = new DefaultHttpClient();
    //HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&"
    //                    + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&"
    //                     + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=4384");
    //HttpResponse response = client.execute(request);
    //BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
    //StringBuilder sb = new StringBuilder();
    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;//w w  w .j a  va  2 s.  co m

    params = "format=json&";
    params += "method=exercises.get&";
    params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key 
    params += "oauth_nonce=123&";
    params += "oauth_signature_method=HMAC-SHA1&";
    Date date = new java.util.Date();
    Timestamp ts = new Timestamp(date.getTime());
    params += "oauth_timestamp=" + ts.getTime() + "&";
    params += "oauth_version=1.0";
    //params += "search_expression=apple"; 

    String params2 = URLEncoder.encode(params);
    base += params2;
    //System.out.println(base);
    String line = "";

    String secret = "76172de2330a4e55b90cbd2eb44f8c63&";
    Mac sha256_HMAC = Mac.getInstance("HMACSHA1");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1");
    sha256_HMAC.init(secret_key);
    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes()));

    //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); 
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api?" + params
            + "&oauth_signature=" + URLEncoder.encode(hash));
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder sb = new StringBuilder();

    //$url = "http://platform.fatsecret.com/rest/server.api?"+params+"&oauth_signature="+URLEncoder.encode(hash);
    //return url;

    while ((line = rd.readLine()) != null) {
        sb.append(line);
        //System.out.println(line);
    }
    //System.out.println(sb.toString());
    return sb;
}

From source file:org.megam.deccanplato.http.TransportMachinery.java

public static TransportResponse post(TransportTools nuts) throws ClientProtocolException, IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(nuts.urlString());
    System.out.println("NUTS" + nuts.toString());
    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            //this if condition is set for twilio Rest API to add credentials to DefaultHTTPClient, conditions met twilio work.
            if (headerEntry.getKey().equalsIgnoreCase("provider")
                    & headerEntry.getValue().equalsIgnoreCase(nuts.headers().get("provider"))) {
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
                                nuts.headers().get("account_sid"), nuts.headers().get("oauth_token")));
            }/*  ww  w .  j  a  va 2  s  .c o  m*/
            //this else part statements for other providers
            else {
                httppost.addHeader(headerEntry.getKey(), headerEntry.getValue());
            }
        }
    }
    if (nuts.fileEntity() != null) {
        httppost.setEntity(nuts.fileEntity());
    }
    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httppost.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httppost.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }
    TransportResponse transportResp = null;
    System.out.println(httppost.toString());
    try {
        HttpResponse httpResp = httpclient.execute(httppost);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httppost.releaseConnection();
    }
    return transportResp;

}

From source file:middleware.HTTPRequest.java

public static void doPostVuelo(String jsonRequest) throws UnsupportedEncodingException, IOException {
    String url = "http://localhost:8084/MVIv2/webapi/vuelos";
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(url);
    StringEntity input = new StringEntity(jsonRequest);
    input.setContentType("application/json");
    postRequest.setEntity(input);/* w w w. j av a  2 s . c om*/

    HttpResponse response = httpClient.execute(postRequest);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("ERROR AL INSERTAR DEL TIPO: " + response.getStatusLine().getStatusCode());
    }

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

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    httpClient.getConnectionManager().shutdown();

}

From source file:au.edu.anu.portal.portlets.basiclti.support.HttpSupport.java

/**
 * Make a POST request with the given Map of parameters to be encoded
 * @param address   address to POST to//from   w  w w  .ja  v  a2  s . co  m
 * @param params   Map of params to use as the form parameters
 * @return
 */
public static String doPost(String address, Map<String, String> params) {

    HttpClient httpclient = new DefaultHttpClient();

    try {

        HttpPost httppost = new HttpPost(address);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();

        for (Map.Entry<String, String> entry : params.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);

        httppost.setEntity(entity);

        HttpResponse response = httpclient.execute(httppost);
        String responseContent = EntityUtils.toString(response.getEntity());

        return responseContent;

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return null;
}

From source file:com.wbtech.dao.NetworkUitlity.java

public static MyMessage post(String url, String data) {
    // TODO Auto-generated method stub
    String returnContent = "";
    MyMessage message = new MyMessage();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {/*w ww. j  a va 2s. c o m*/
        StringEntity se = new StringEntity("content=" + data, HTTP.UTF_8);
        Log.d("postdata", "content=" + data);
        se.setContentType("application/x-www-form-urlencoded");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();

        String returnXML = EntityUtils.toString(response.getEntity());
        returnContent = URLDecoder.decode(returnXML);
        switch (status) {
        case 200:
            message.setFlag(true);
            message.setMsg(returnContent);
            break;

        default:
            Log.e("error", status + returnContent);
            message.setFlag(false);
            message.setMsg(returnContent);
            break;
        }
    } catch (Exception e) {
        JSONObject jsonObject = new JSONObject();

        if (e.getMessage().equalsIgnoreCase("no route to host")) {
            try {
                jsonObject.put("err", "??,???");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        else if (e.getMessage().equalsIgnoreCase("network unreachable")
                || e.getMessage().equalsIgnoreCase("www.cobub.com")) {
            try {
                jsonObject.put("err", "");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        else {
            try {
                jsonObject.put("err", "");
                returnContent = jsonObject.toString();
                message.setFlag(false);
                message.setMsg(returnContent);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

    }
    return message;
}

From source file:org.wso2.dss.integration.test.odata.ODataTestUtils.java

public static Object[] sendPOST(String endpoint, String content, Map<String, String> headers)
        throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(endpoint);
    for (String headerType : headers.keySet()) {
        httpPost.setHeader(headerType, headers.get(headerType));
    }/* w  w  w  .j a  va2s  .  c om*/
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPost.setHeader("Content-Type", "application/json");
        }
        httpPost.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPost);
    if (httpResponse.getEntity() != null) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = reader.readLine()) != null) {
            response.append(inputLine);
        }
        reader.close();
        return new Object[] { httpResponse.getStatusLine().getStatusCode(), response.toString() };
    } else {
        return new Object[] { httpResponse.getStatusLine().getStatusCode() };
    }
}

From source file:markson.visuals.sitapp.JSONfunctions.java

public static JSONObject getJSONfromURL(String url) {

    //initialize//www . ja  v  a 2s . c  om
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    //convert response to string
    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();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

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

    return jArray;
}

From source file:net.ecfirm.ec.ec1.net.EcNetHelper.java

public static DefaultHttpClient getThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    //////////from   w ww . j a va2 s.  co m
    client.getParams().setParameter("http.protocol.expect-continue", false);
    client.getParams().setParameter("http.connection.timeout", EcConst.NET_HTTP_CONN_TIMEOUT);
    //client.getParams().setParameter("http.socket.timeout", );
    ////////
    HttpParams params = client.getParams();
    ////////
    ConnManagerParams.setMaxTotalConnections(params, EcConst.NET_HTTP_CONN);
    ConnPerRouteBean connPerRoute = new ConnPerRouteBean(EcConst.NET_HTTP_CONN_PER_ROUTE);
    HttpHost localhost = new HttpHost("localhost", 80);
    connPerRoute.setMaxForRoute(new HttpRoute(localhost), EcConst.NET_HTTP_CONN_PER_ROUTE);
    ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);
    mgr.getSchemeRegistry().register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    mgr.getSchemeRegistry().register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ////////
    client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
    return client;
}

From source file:WSpatern.ValidTokenWS.java

public void TokenStats(String token) {
    try {/*  w  w  w.j  a  va 2 s.  co m*/
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet("http://documenta-dms.com/DMSWS/api/v1/login/" + token);
        HttpResponse response = client.execute(get);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {

            System.out.println(line);
            parseXML(line);

        }
    } catch (IOException ex) {
        Logger.getLogger(ValidTokenWS.class.getName()).log(Level.SEVERE, null, ex);
    }

}