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:app.wz.HttpClient.java

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

    try {// ww  w.ja  v a 2 s  .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");
        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) {
            return EntityUtils.toString(entity);
            //            // 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.wms.opensource.images3android.images3.ImageS3Service.java

private static HttpClient getClient() {
    if (client == null) {
        client = new DefaultHttpClient();
    }
    return client;
}

From source file:com.codingrhemes.steamsalesmobile.JSON.java

public static String readJSONFeed(String URL) {
    StringBuilder stringBuilder = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(URL);
    try {/*from   w w w  . j  ava 2  s .  co  m*/
        HttpResponse response = httpClient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream inputStream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            inputStream.close();
        } else {
            Log.d("JSON", "Failed to download file");
        }
    } catch (Exception e) {
        Log.d("readJSONFeed", e.getLocalizedMessage());
    }
    return stringBuilder.toString();
}

From source file:de.siemens.quantarch.personService.PersonServiceClient.java

public static final long getPerson(String name, String email, long projectId, String personServiceUrl) {
    long userId = 0;
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(personServiceUrl + "/post_user_id");
    try {//from   www . j  a  v a2s. c o  m
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("projectID", Long.toString(projectId)));
        nameValuePairs.add(new BasicNameValuePair("name", name));
        nameValuePairs.add(new BasicNameValuePair("email", email));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        // read output
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = rd.readLine()) != null) {
            builder.append(line);
        }

        JSONObject json = JSONObject.fromObject(builder.toString());
        userId = json.getLong("id");
        return userId;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return userId;
}

From source file:io.selendroid.server.util.HttpClientUtil.java

public static HttpClient getHttpClient() {
    return new DefaultHttpClient();
}

From source file:com.swetha.easypark.EasyParkHttpClient.java

private static HttpClient getHttpClient() {

    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();

        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }//from   w w w. j  a va2s.  com

    return mHttpClient;
}

From source file:com.safecell.networking.GetLicenseKey.java

public String getRequest() {
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout

    String url = URLs.REMOTE_URL + "api/1/license_classes";

    HttpGet postRequest = new HttpGet(url);
    postRequest.setHeader("Content-Type", "application/json");

    String result = null;/*w  w  w .j  a  va  2  s.c  om*/
    try {
        response = client.execute(postRequest);
        result = getResponseBody();

        if (response.getStatusLine().getStatusCode() != 200) {
            response = null;
            result = null;
            failureMessage = "The licenses downlaod failed because of an unexpected error.";
        }

    } catch (Exception e) {
        response = null;
        result = null;
        failureMessage = "The licenses downlaod failed because of an unexpected error.";
    }

    return result;

}

From source file:wvw.utils.pc.HttpHelper.java

public static String post(String url, JSONArray headers, String data) {
    HttpPost httpPost = new HttpPost(url);

    for (int i = 0; i < headers.length(); i++) {
        JSONArray header = headers.getJSONArray(i);

        httpPost.addHeader(header.getString(0), header.getString(1));
    }//from w  ww  .  ja v a2 s.  c o m

    String ret = null;
    try {
        httpPost.setEntity(new StringEntity(data));

        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);

        StatusLine status = response.getStatusLine();

        switch (status.getStatusCode()) {

        case 200:
            ret = IOUtils.readFromStream(response.getEntity().getContent());

            break;

        default:
            ret = genError(status.getReasonPhrase());

            break;
        }

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

        ret = genError(e.getClass() + ": " + e.getMessage());
    }

    return ret;
}

From source file:org.wwscc.registration.attendance.Attendance.java

/**
 * Retrieve the attendance report from the main host
 * @param host the hostname to retrieve from
 * @throws IOException //from  www  . ja v a  2  s  . com
 * @throws URISyntaxException 
 * @throws UnsupportedEncodingException 
 */
public static void getAttendance(String host) throws IOException, URISyntaxException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpclient.getParams(), "Scorekeeper/2.0");

    MonitorProgressStream monitor = new MonitorProgressStream("Download Attendance");
    monitor.setProgress(1);
    monitor.setNote("Initialize");

    HttpPost request = new HttpPost(new URI("http", host, "/history/attendance", null));
    File temp = File.createTempFile("attendance", "tmp");
    monitor.setProgress(2);
    monitor.setNote("Connecting/Calcuation...");

    HttpEntity download = httpclient.execute(request).getEntity();
    monitor.setProgress(3);
    monitor.setNote("Downloading...");

    FileOutputStream todisk = new FileOutputStream(temp);
    monitor.setStream(todisk, download.getContentLength());
    download.writeTo(monitor);
    FileUtils.copyFile(temp, defaultfile);
}

From source file:org.npr.api.HttpHelper.java

/**
 * A helper function to grab content from a URL.
 *
 * @param url URL of the item to download
 *
 * @return an input stream to the content. The caller is responsible for
 * closing the stream. Content will be null in the case of errors.
 * @throws java.io.IOException if an error occurs loading the url
 *///from  w  ww .  j  a  v  a 2 s. c om
public static InputStream download(String url) throws IOException {
    InputStream data = null;
    Log.d(LOG_TAG, "Starting download: " + url);
    HttpClient http = new DefaultHttpClient();
    HttpGet method = new HttpGet(url);

    try {
        HttpResponse response = http.execute(method);
        data = response.getEntity().getContent();
    } catch (IllegalStateException e) {
        Log.e(LOG_TAG, "error downloading", e);
    }
    Log.d(LOG_TAG, "Download complete");
    return data;
}