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.TaxiDriver.jy.DriverQuery.java

public static JSONObject getJobInfo(String job_id) {

    HttpPost postJob = new HttpPost(HttpHelper.domain + "job.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  a2  s  .com

        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("job_id", job_id));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));

        HttpResponse response = clientJob.execute(postJob);
        String jsonString = HttpHelper.request(response);
        JSONArray jArray = new JSONArray(jsonString);
        JSONObject json = jArray.getJSONObject(0);

        return json;
    } catch (ClientProtocolException e) {
        return null;
    } catch (IOException e) {
        return null;
    } catch (JSONException e) {
        return null;
    }

}

From source file:co.cask.cdap.gateway.handlers.metrics.MetricsSuiteTestBase.java

public static HttpResponse doPost(String resource, String body, Header[] headers) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(MetricsSuiteTestBase.getEndPoint(resource));
    if (body != null) {
        post.setEntity(new StringEntity(body));
    }//from   w  w  w  .  j  a v  a  2  s  . co  m

    if (headers != null) {
        post.setHeaders(ObjectArrays.concat(AUTH_HEADER, headers));
    } else {
        post.setHeader(AUTH_HEADER);
    }
    return client.execute(post);
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static JSONObject doPost(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;/*from w ww. j av  a2 s .com*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            logger.info("post result is :{}", result);
            if (!Global.isEmpty(result)) {
                response = JSONObject.fromObject(result);
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

From source file:com.thoughtmetric.tl.TLLib.java

public static String parseQuoteText(HtmlCleaner cleaner, URL url, TLHandler handler, Context context)
        throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCookieStore(cookieStore);

    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    InputStream is = response.getEntity().getContent();

    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    return parseTextArea(br);
}

From source file:messenger.YahooFinanceAPI.java

public static String httpget(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }/*  ww  w. jav  a2 s  .c om*/

    HttpGet httpget = new HttpGet(url);
    // Override the default policy for this request

    httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpResponse response = null;
    String responseString = null;
    try {
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cookiestore = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else {
            System.out.println(response.getStatusLine());
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}

From source file:org.dvbviewer.controller.io.ServerRequest.java

/**
 * Execute get./*from   www.  j  a va 2 s. c  o  m*/
 *
 * @param client the client
 * @param request the request
 * @return the http response
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ClientProtocolException the client protocol exception
 * @throws AuthenticationException the authentication exception
 * @author RayBa
 * @date 05.07.2012
 */
private static HttpResponse executeGet(DefaultHttpClient client, HttpGet request, boolean log)
        throws Exception {
    if (log) {
        Log.d(ServerRequest.class.getSimpleName(), "request: " + request.getRequestLine());
    }
    HttpResponse response = client.execute(request);
    StatusLine status = response.getStatusLine();
    Log.d(ServerRequest.class.getSimpleName(), "statusCode: " + status.getStatusCode());

    switch (status.getStatusCode()) {

    case HttpStatus.SC_UNAUTHORIZED:
        throw new AuthenticationException();

    default:
        break;
    }
    return response;
}

From source file:org.openo.nfvo.monitor.dac.util.APIHttpClient.java

@SuppressWarnings({ "resource" })
public static String doPost2Str(String url, JSONObject json, String token) {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    String response = null;/* ww  w. ja v  a2s.c  om*/
    try {
        if (null != json) {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json"); // set contentType
            post.setEntity(s);
        }
        if (!Global.isEmpty(token)) {
            post.addHeader("X-Auth-Token", token);
        }
        HttpResponse res = client.execute(post);
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || res.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            String result = EntityUtils.toString(res.getEntity());
            logger.info("post result is :{}", result);
            if (!Global.isEmpty(result)) {
                response = result;
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

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

public static Photo handleResult(String photoId) {

    String result = null;/* w w w  .  j a  v a2  s . c  o  m*/

    try {

        Log.e("URL DSAHDKJA", getWeb_Url(photoId));

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpPost = new HttpGet(getWeb_Url(photoId));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        result = EntityUtils.toString(httpEntity);

        if (result != null && result.length() > 0) {
            JSONObject jobject = new JSONObject(result);

            String state = jobject.getString("stat");

            if (state.equalsIgnoreCase(STAT_OK)) {

                // Photo Object
                String photo = jobject.getString("photo");
                JSONObject jobjectPhoto = new JSONObject(photo);

                String id = jobjectPhoto.getString("id");
                String secret = jobjectPhoto.getString("secret");
                String server = jobjectPhoto.getString("server");
                String farm = jobjectPhoto.getString("farm");
                String license = jobjectPhoto.getString("license");

                String originalsecret = "", originalformat = "";
                if (jobjectPhoto.has("originalsecret")) {
                    originalsecret = jobjectPhoto.getString("originalsecret");
                    originalformat = jobjectPhoto.getString("originalformat");
                }

                // Author Object
                String owner = jobjectPhoto.getString("owner");
                JSONObject jobjectOwner = new JSONObject(owner);

                String nsid = jobjectOwner.getString("nsid");
                String username = jobjectOwner.getString("username");
                String realname = jobjectOwner.getString("realname");

                String iconFarm = "", iconServer = "";
                if (jobjectOwner.has("iconfarm")) {
                    iconFarm = jobjectOwner.getString("iconfarm");
                }
                if (jobjectOwner.has("iconserver")) {
                    iconServer = jobjectOwner.getString("iconserver");
                }

                // Title Object
                String titleObject = jobjectPhoto.getString("title");
                JSONObject jobjectTitle = new JSONObject(titleObject);

                String title = jobjectTitle.getString("_content");

                // Description Object
                String desObject = jobjectPhoto.getString("description");
                JSONObject jobjectDescription = new JSONObject(desObject);
                String description = jobjectDescription.getString("_content");

                // Local Object

                String location = "", locality = "", region = "", country = "";

                if (jobjectPhoto.has("location")) {
                    location = jobjectPhoto.getString("location");
                    JSONObject jobjectLocation = new JSONObject(location);

                    // Locality
                    String localityObject = "";
                    if (jobjectLocation.has("locality")) {
                        localityObject = jobjectLocation.getString("locality");
                        JSONObject jobjectlocality = new JSONObject(localityObject);
                        locality = jobjectlocality.getString("_content");
                    }

                    // Region
                    if (jobjectLocation.has("region")) {
                        String regionObject = jobjectLocation.getString("region");
                        JSONObject jobjectregion = new JSONObject(regionObject);
                        region = jobjectregion.getString("_content");
                    }

                    // Country
                    if (jobjectLocation.has("country")) {
                        String countryObject = jobjectLocation.getString("country");
                        JSONObject jobjectcountry = new JSONObject(countryObject);
                        country = jobjectcountry.getString("_content");
                    }

                }

                String url = "";
                if (jobjectPhoto.has("urls")) {
                    String urls = jobjectPhoto.getString("urls");
                    JSONObject jobjectUrls = new JSONObject(urls);

                    if (jobjectUrls.has("url")) {

                        String arrayUrlObject = jobjectUrls.getString("url");
                        JSONArray jarraytUrl = new JSONArray(arrayUrlObject);

                        JSONObject jsonObjectUrl = jarraytUrl.getJSONObject(0);

                        if (jsonObjectUrl.has("_content"))
                            url = jsonObjectUrl.getString("_content");
                    }

                }

                Photo photoObject = new Photo(id, secret, server, farm, license, originalsecret, originalformat,
                        nsid, username, realname, title, description, locality, region, country, url,
                        iconServer, iconFarm, false, "");
                return photoObject;
            }

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

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

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

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

    }
    return null;

}

From source file:org.corfudb.sharedlog.ClientLib.java

static public CorfuConfiguration pullConfigUtil(String master) throws CorfuException {
    CorfuConfiguration pullCM = null;// ww  w  .ja  va 2  s  .  c  om
    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {
        HttpGet httpget = new HttpGet(master);

        System.out.println("Executing request: " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);

        System.out.println("pullConfig from master: " + response.getStatusLine());

        pullCM = new CorfuConfiguration(response.getEntity().getContent());
    } catch (ClientProtocolException e) {
        throw new InternalCorfuException("cannot pull configuration");
    } catch (IOException e) {
        throw new InternalCorfuException("cannot pull configuration");
    }
    return pullCM;
}

From source file:com.bourke.kitchentimer.utils.Utils.java

public static void notifyServer(final String serverUrl) {
    new Thread(new Runnable() {
        @Override/*  w  ww  .  j ava2s. c om*/
        public void run() {
            try {
                Log.d("Utils", "notifyServer:" + serverUrl);
                DefaultHttpClient httpclient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(serverUrl);

                URL url = new URL(serverUrl);
                String userInfo = url.getUserInfo();
                if (userInfo != null) {
                    httpget.addHeader("Authorization",
                            "Basic " + Base64.encodeToString(userInfo.getBytes(), Base64.NO_WRAP));
                }

                HttpResponse response = httpclient.execute(httpget);
                response.getEntity().getContent().close();
                httpclient.getConnectionManager().shutdown();

                int status = response.getStatusLine().getStatusCode();
                if (status < 200 || status > 299) {
                    throw new Exception(response.getStatusLine().toString());
                }
            } catch (Exception ex) {
                Log.e("Utils", "Error notifying server: ", ex);
            }
        }
    }).start();
}