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.pti.mates.ServerUtilities.java

private static void updatePreferences(JSONObject user, Context ctx, String fbid) {
    DefaultHttpClient client = new MyHttpClient(ctx);
    HttpPost post = new HttpPost("https://54.194.14.115:443/upload");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("user", user.toString()));
    try {//from  ww  w.j  a va 2 s . c  o  m
        post.setHeader("Content-type", "application/json");
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpResponse postResponse;
    try {
        postResponse = client.execute(post);
        HttpEntity responseEntity = postResponse.getEntity();
        InputStream is = responseEntity.getContent();
    } catch (ClientProtocolException e) {
        Log.e("ERROR", e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("ERROR", e.toString());
        s = "ERROR: " + e.toString() + " :(";
    }
    Log.d("CHIVATO", "FIN THREAD");
}

From source file:hpcc.hut.edu.vn.ocr.ocrserviceconnector.HpccOcrServiceConnector.java

public static String postToOcrService(byte[] data, int size, int imgw, int imgh, String lang, int psm,
        boolean isPrePostProcess) {
    System.out.println("Sent data: w = " + imgw + ", h = " + imgh + ", psm = " + psm + ", process: "
            + isPrePostProcess + ", with lang: " + lang);
    String result = "";

    try {/*w  ww . jav a2  s  . c  o m*/
        HttpParams httpParamenters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParamenters, 30000);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParamenters);
        HttpPost postRequest = new HttpPost(HOST);

        ByteArrayBody bab = new ByteArrayBody(data, "input.jpg");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("image", bab);
        reqEntity.addPart("size", new StringBody("" + size)); // size to
        // check if
        // decompress
        // fail
        reqEntity.addPart("width", new StringBody("" + imgw));
        reqEntity.addPart("height", new StringBody("" + imgh));
        reqEntity.addPart("lang", new StringBody(lang));
        reqEntity.addPart("psm", new StringBody("" + psm));
        reqEntity.addPart("process", new StringBody("" + isPrePostProcess));

        postRequest.setEntity(reqEntity);

        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        result = s.toString();
        System.out.println("result in Json: " + result);
    } catch (Exception e) {
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());
        return null;
    }
    return result;

}

From source file:com.ada.utils.Log.java

public static void remote(final String msg) {
    if (mRemoteUrl == null) {
        return;//w w w .  j ava2s .  c  o  m
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(mRemoteUrl);

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("package_name", mPackageName));
                params.add(new BasicNameValuePair("package_version", mPackageVersion));
                params.add(new BasicNameValuePair("phone_model", Build.MODEL));
                params.add(new BasicNameValuePair("sdk_version", Build.VERSION.RELEASE));
                params.add(new BasicNameValuePair("message", msg));

                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                httpClient.execute(httpPost);
            } catch (Exception e) {
            }
        }
    }).start();
}

From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java

protected static HttpResponse doPut(String resource, String body) throws Exception {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(getEndPoint(resource));
    if (body != null) {
        put.setEntity(new StringEntity(body));
    }//from  www .  ja  va  2  s. c om
    put.setHeader(AUTH_HEADER);
    return client.execute(put);
}

From source file:com.netflix.raigad.utils.SystemUtils.java

public static String runHttpPostCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;// w  w w .j  ava  2 s. c  om
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 1000;
        int timeoutSocket = 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        client.setParams(httpParameters);

        HttpPost postRequest = new HttpPost(url);
        if (StringUtils.isNotEmpty(jsonBody))
            postRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
        postRequest.setHeader("Content-type", "application/json");

        HttpResponse resp = client.execute(postRequest);

        if (resp == null || resp.getEntity() == null) {
            throw new ESHttpException("Unable to execute POST URL (" + url
                    + ") Exception Message: < Null Response or Null HttpEntity >");
        }

        isStream = resp.getEntity().getContent();

        if (resp.getStatusLine().getStatusCode() != 200) {

            throw new ESHttpException("Unable to execute POST URL (" + url + ") Exception Message: ("
                    + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")");
        }

        return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
        logger.debug("POST URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
        throw new ESHttpException(
                "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")");
    } finally {
        if (isStream != null)
            isStream.close();
    }
    return return_;
}

From source file:com.TaxiDriver.jy.DriverQuery.java

public static String[][] pingForJobAndPosition(String driver_id, int lat, int longi,
        ArrayList<Object> rejectList, String av) {
    int jobCount = 0;
    int j = 0;/*w w  w .  jav  a  2  s .  c  o m*/

    HttpPost postJob = new HttpPost(HttpHelper.domain + "pingjob.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);

    JSONArray jArray = null;
    try {
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("driver_id", driver_id));
        infoJob.add(new BasicNameValuePair("lat", Integer.valueOf(lat).toString()));
        infoJob.add(new BasicNameValuePair("longi", Integer.valueOf(longi).toString()));
        infoJob.add(new BasicNameValuePair("avail", av));
        postJob.setEntity(new UrlEncodedFormEntity(infoJob));

        HttpResponse response = clientJob.execute(postJob);
        String jsonString = HttpHelper.request(response);
        jArray = new JSONArray(jsonString);
        if (jArray != null) {
            jobCount = jArray.length();
        }
    } catch (Exception ex) {

    }

    if (jArray != null && av.equals("1")) {
        String[][] joblist = new String[jobCount][9];

        String geoadd = null;

        try {
            for (int i = 0; i < jobCount; i++) {
                JSONObject json = jArray.getJSONObject(i);

                /*
                 * Geocoder geocoder = new Geocoder(c, Locale.getDefault()); try { List<Address> address = geocoder.getFromLocation( json.getInt("lat") /
                 * 1E6, json.getInt("longi") / 1E6, 1); if (address.size() > 0) { geoadd = ""; for (int j = 0; j < address.get(0) .getMaxAddressLineIndex();
                 * j++) { geoadd += address.get(0).getAddressLine(j) + "\n"; } } } catch (IOException e) { } finally { }
                 */

                if (rejectList != null && rejectList.contains(json.getString("job_id"))) {
                } else {
                    joblist[j][0] = json.getString("job_id");
                    joblist[j][1] = json.getString("lat");
                    joblist[j][2] = json.getString("longi");

                    joblist[j][3] = "";
                    joblist[j][4] = json.getString("pickup");
                    joblist[j][5] = json.getString("destination");
                    joblist[j][6] = String.valueOf(getServerTime() - json.getInt("datetime"));
                    joblist[j][7] = String.valueOf(json.getInt("number"));
                    joblist[j][8] = json.getString("driver_id");
                    j++;
                }
            }

        } catch (JSONException e) {

        }

        if (j == 0) {

            return null;
        } else {
            return joblist;
        }
    } else {

        return null;
    }

}

From source file:com.pti.mates.ServerUtilities.java

public static void sendPreferences(SharedPreferences prefs, Context ctx) {
    //enviar preferencies al server
    Log.v(LogConstants.LOG_SERVERUTILITIES, "radius = " + prefs.getString(Common.RADIUS_KEY, "Empty"));
    Log.v(LogConstants.LOG_SERVERUTILITIES, "gender = " + prefs.getString(Common.GENDER_KEY, "Empty"));
    Log.v(LogConstants.LOG_SERVERUTILITIES,
            "interested in = " + prefs.getString(Common.INTERESTED_IN_KEY, "Empty"));
    String fbid = Common.getFBID();
    DefaultHttpClient client = new MyHttpClient(ctx);
    HttpPost post = new HttpPost("https://54.194.14.115:443/user");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
    nameValuePairs.add(new BasicNameValuePair("id", fbid));
    try {/*w ww  .j  ava2s  .  co m*/
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Execute the Post call and obtain the response
    HttpResponse postResponse;
    JSONObject user;
    try {
        postResponse = client.execute(post);
        HttpEntity responseEntity = postResponse.getEntity();
        InputStream is = responseEntity.getContent();
        try {
            user = new JSONObject(convertStreamToString(is));
            user.put("gender", prefs.getString(Common.GENDER_KEY, "Empty"));
            user.put("interested_in", prefs.getString(Common.INTERESTED_IN_KEY, "Empty"));
            user.put("distance", prefs.getString(Common.RADIUS_KEY, "Empty"));
            updatePreferences(user, ctx, fbid);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (ClientProtocolException e) {
        Log.e("ERROR", e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("ERROR", e.toString());
        s = "ERROR: " + e.toString() + " :(";
    }
    Log.d("CHIVATO", "FIN THREAD");

}

From source file:com.TaxiDriver.jy.DriverQuery.java

public static String getETA(String url, String fromLat, String fromLongi, String toLat, String toLongi,
        String type) {// w  w w.  j  av a2 s.  c o m

    HttpPost postJob = new HttpPost(HttpHelper.domain + "getduration.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 {
        List<NameValuePair> infoJob = new ArrayList<NameValuePair>(2);
        infoJob.add(new BasicNameValuePair("url", url));

        infoJob.add(new BasicNameValuePair("fromLongi", fromLongi));
        infoJob.add(new BasicNameValuePair("fromLat", fromLat));
        infoJob.add(new BasicNameValuePair("toLongi", toLongi));
        infoJob.add(new BasicNameValuePair("toLat", toLat));
        infoJob.add(new BasicNameValuePair("type", type));

        postJob.setEntity(new UrlEncodedFormEntity(infoJob));

        HttpResponse response = clientJob.execute(postJob);

        String jsonString = HttpHelper.request(response);
        String duration = jsonString.trim();

        return duration;

    } catch (Exception ex) {
        return null;
    }

}

From source file:com.mingsoft.util.proxy.Proxy.java

/**
 * get//  w  w  w  .  j  a  va  2s.  c o m
 * 
 * @param url
 *            ?<br>
 * @param header
 *            ?Header new Header()<br>
 * @param params
 *            ?<br>
 * @return Result 
 */
public static Result get(String url, com.mingsoft.util.proxy.Header header, Map params) {
    //log.info("?" + url);
    // Httpclient
    DefaultHttpClient client = new DefaultHttpClient();
    // ??
    url = url + (null == params ? "" : assemblyParameter(params));
    // get
    HttpGet httpGet = new HttpGet(url);
    // cookie?()
    httpGet.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    // ?
    if (null != header && header.getHeaders().size() > 0) {
        httpGet.setHeaders(Proxy.assemblyHeader(header.getHeaders()));
    }
    // ?HttpResponse
    HttpResponse response;
    try {
        response = client.execute(httpGet);
        // 
        // httpGet.abort();
        // HttpEntity
        HttpEntity entity = response.getEntity();
        // ??
        Result result = new Result();
        // cookie
        result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
        // ?
        result.setStatusCode(response.getStatusLine().getStatusCode());
        // 
        result.setHeaders(response.getAllHeaders());
        // ?
        result.setHttpEntity(entity);
        return result;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        log.error(e.getMessage());
    }
    return null;
}

From source file:com.emc.cto.ridagent.rid.test.TestScript.java

public static String httpSend(String output, String destURL) throws ParserConfigurationException, SAXException {

    /* Set up TLS mutual authentication */

    KeyStore keystore = null;//from w ww .  ja  va  2 s  .c om
    String docid = null;
    try {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream keystoreInput = null;
    try {
        keystoreInput = new FileInputStream(m_keystorePath);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        keystore.load(keystoreInput, m_keystorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Keystore has " + keystore.size() + " keys");
        }
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    KeyStore truststore = null;
    try {
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    InputStream truststoreInput = null;
    try {
        truststoreInput = new FileInputStream(m_truststorePath);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        truststore.load(truststoreInput, m_truststorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    SSLSocketFactory schemeSocketFactory = null;

    try {
        schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore);
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory));
    final HttpParams httpParams = new BasicHttpParams();
    DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry),
            httpParams);

    /* Prepare the request to send */

    Map<String, Object> responseMap = new HashMap<String, Object>();

    HttpEntity request = new StringEntity(output, ContentType.TEXT_XML);

    //Create POST method
    HttpPost postMethod = new HttpPost(destURL);
    postMethod.setHeader("User-Agent", "EMC RID System");
    postMethod.setHeader("Content-Type", "text/xml");
    postMethod.setEntity(request);

    /* POST the request and process the response */
    HttpResponse httpResponse = null;
    int code;

    try {
        httpResponse = httpClient.execute(postMethod);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (httpResponse.getEntity() != null) {

        code = httpResponse.getStatusLine().getStatusCode();

        try {
            InputStream xml = httpResponse.getEntity().getContent();

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(xml);
            docid = doc.getElementsByTagName("iodef:IncidentID").item(0).getTextContent();
            System.out.println("ID of the newly created document   " + docid);
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        responseMap.put("success", true);
        responseMap.put("statusCode", code);

    } else {
        responseMap.put("success", false);
        responseMap.put("errorMessage", "Send failed (fill in exception)");
    }

    return docid;
}