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:com.alibaba.flink.utils.MetricsMonitor.java

public static Map httpResponse(String url) {
    Map ret;//w w w  .  j a  v  a2  s  .c  o  m
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);
        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());
        }

        String data = EntityUtils.toString(response.getEntity());

        ret = (Map) Utils.from_json(data);

        httpClient.getConnectionManager().shutdown();

    } catch (IOException e) {
        ret = errorMsg(e.getMessage());
    }
    return ret;
}

From source file:com.roncoo.pay.permission.utils.RoncooHttpClientUtils.java

/**
 *  API/*from  w  w w.j a v a 2  s.  c  o  m*/
 * 
 * @param parameters
 * @return
 */
@SuppressWarnings({ "resource", "deprecation" })
public static String post(String url, String parameters) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost method = new HttpPost(url);
    String body = null;

    if (method != null & parameters != null && !"".equals(parameters.trim())) {
        try {

            // NameValuePair??
            method.addHeader("Content-type", "application/json; charset=utf-8");
            method.setHeader("Accept", "application/json");
            method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));

            HttpResponse response = httpClient.execute(method);

            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                return "1";// 1
            }

            // Read the response body
            body = EntityUtils.toString(response.getEntity());

        } catch (IOException e) {
            // 
            return "2";
        } finally {
        }

    }
    return body;
}

From source file:geert.stef.sm.beheerautokm.AddRitTask.java

public static HttpResponse hitUrl(String url) {
    try {//from   w ww . jav a  2  s. c o  m
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(new HttpGet(url));
        return response;
    } catch (Exception e) {
        //Log.("[GET REQUEST]", "Network exception", e);
        return null;
    }
}

From source file:org.hobbit.spatiotemporalbenchmark.transformations.value.AddressFromFoursquareApi.java

public static String getAddress(double latitude, double longitude) {
    String strAddress = "";
    String point = latitude + "," + longitude;

    String url = "https://api.foursquare.com/v2/venues/search?ll=" + latitude + "," + longitude
            + "&oauth_token=5TJR4WQZSOW0ZWTE4ENMXKO3Y415252GITEMRPQIVPMEGCYK&v=20120723&limit=1&accept-language=en";

    HttpPost httppost = new HttpPost(url);
    HttpClient httpclient = new DefaultHttpClient();
    String result = "";
    try {//from   w  w  w .  j  a  v a  2  s  . co  m
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntityGet = response.getEntity();
        if (resEntityGet != null) {
            result = EntityUtils.toString(resEntityGet);
        }
    } catch (Exception e) {
        System.out.println("Exception:" + e);
    }
    try {
        /*Keeps the first address form the results*/
        if (result != null) {
            JSONObject json = new JSONObject(result);
            JSONObject jo = json.getJSONObject("response");
            JSONArray ja = jo.getJSONArray("venues");
            for (int i = 0; i < 1; i++) {
                strAddress = ja.getJSONObject(i).getJSONObject("location").getJSONArray("formattedAddress")
                        .toString();
                strAddress = strAddress.replace("},{", ",").replace("[", "").replace("]", "").replace("\"", "");
            }
        }
    } catch (Exception e) {
    }
    try {
        if (!strAddress.equals("")) {
            pointAddressMap.put(point, strAddress);
            FileUtils.writeStringToFile(f, point + "=" + strAddress + "\n", true);
        }
    } catch (IOException ex) {
        Logger.getLogger(CoordinatesToAddress.class.getName()).log(Level.SEVERE, null, ex);
    }
    return strAddress;
}

From source file:com.socioffice.grabmenu.model.JSONRequest.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {// w  w  w .  j a  v  a 2s .c o  m
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");

        // only set this parameter if you would like to use gzip compression
        httpPostRequest.setHeader("Accept-Encoding", "gzip");

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and
            // "]"

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<jsonobject>\n" + jsonObjRecv.toString() + "\n</jsonobject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static HttpEntity getEntity(String uri, ArrayList<BasicNameValuePair> params, int method)
        throws ClientProtocolException, IOException {
    mClient = new DefaultHttpClient();
    HttpUriRequest request = null;//from  w  ww .ja v  a  2 s .co m
    switch (method) {
    case METHOD_GET:
        StringBuilder sb = new StringBuilder(uri);
        if (params != null && !params.isEmpty()) {
            sb.append("?");
            for (BasicNameValuePair param : params) {
                sb.append(param.getName()).append("=").append(URLEncoder.encode(param.getValue(), "UTF_8"))
                        .append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        request = new HttpGet(sb.toString());
        break;
    case METHOD_POST:
        HttpPost post = new HttpPost(uri);
        if (params != null && !params.isEmpty()) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF_8");
            post.setEntity(entity);
        }
        request = post;
        break;
    }
    mClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
    mClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
    HttpResponse response = mClient.execute(request);
    System.err.println(response.getStatusLine().toString());
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response.getEntity();
    }
    return null;
}

From source file:com.mmj.app.common.util.SpiderHtmlUtils.java

/**
 * ?URLhtml?//  www .j a  va  2 s.com
 * 
 * @param url
 * @return
 */
public static String getHtmlByUrl(String url) {
    if (StringUtils.isEmpty(url)) {
        return null;
    }
    String html = null;
    HttpClient httpClient = new DefaultHttpClient();// httpClient
    HttpUriRequest httpget = new HttpGet(url);// get?URL
    httpget.setHeader("Connection", "keep-alive");
    httpget.setHeader("Referer", "http://www.baidu.com");
    httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    httpget.setHeader("User-Agent",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36");
    try {
        HttpResponse responce = httpClient.execute(httpget);// responce
        int responseCode = responce.getStatusLine().getStatusCode();// ?
        if (responseCode == HttpStatus.SC_OK || responseCode == HttpStatus.SC_MOVED_PERMANENTLY
                || responseCode == HttpStatus.SC_MOVED_TEMPORARILY) {// 200 ?
            // 
            HttpEntity entity = responce.getEntity();
            if (entity != null) {
                html = EntityUtils.toString((org.apache.http.HttpEntity) entity);// html??
            }
        }
    } catch (Exception e) {
        logger.error("SpiderHtmlUtils:getHtmlByUrl sprider url={} error!!!", url);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return html;
}

From source file:ca.dal.cs.csci4126.quizboard.library.HttpClient.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {//from w ww  .  j  a va 2 s  .  co m
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}

From source file:com.codebutler.rsp.Util.java

public static String getURL(URL url, String password) throws Exception {
    Log.i("Util.getURL", url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (password != null && password.length() > 0) {
        UsernamePasswordCredentials creds;
        creds = new UsernamePasswordCredentials("user", password);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    }//from  w  w  w . j  a va  2s . c  om

    HttpGet method = new HttpGet(url.toURI());
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    return client.execute(method, responseHandler);
}

From source file:com.example.montxu.magik_repair.HttpClient.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {//from  w w w.  j av  a  2  s  .c om
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString = convertStreamToString(instream);
            instream.close();
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;
        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.

        e.printStackTrace();
    }

    return null;
}