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:org.openo.nfvo.monitor.umc.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;//from  ww  w  .j av a  2  s . co m
    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());
            if (!Global.isEmpty(result)) {
                response = result;
            } else {
                response = null;
            }
        }
    } catch (Exception e) {
        logger.error("Exception", e);
    }
    return response;
}

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

public static TagNode TagNodeFromURLEx2(HtmlCleaner cleaner, URL url, Handler handler, Context context,
        String fullTag, boolean login) throws IOException {

    handler.sendEmptyMessage(PROGRESS_CONNECTING);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (login) {/*from   ww  w  .j av  a  2s  . com*/
        httpclient.setCookieStore(cookieStore);
    }
    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    HttpEntity httpEntity = response.getEntity();
    InputStream is = httpEntity.getContent();
    return TagNodeFromURLHelper(is, fullTag, handler, context, cleaner);
}

From source file:org.xwiki.android.authenticator.rest.XWikiConnector.java

public static String userSignIn(String server, String user, String pass, String authType) throws Exception {

    Log.d("xwiki", "userSignIn");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    String url = server + "/rest/";

    HttpGet httpGet = new HttpGet(url);

    httpGet.addHeader("Authorization",
            "Basic " + Base64.encodeToString((user + ':' + pass).getBytes(), Base64.NO_WRAP));

    HttpParams params = new BasicHttpParams();
    params.setParameter("username", user);
    params.setParameter("password", pass);
    httpGet.setParams(params);//from ww w .ja v  a 2s .c  o m

    HttpResponse response = httpClient.execute(httpGet);
    int error = response.getStatusLine().getStatusCode();
    if (error != 200) {
        throw new Exception("Error signing-in [" + url + "] with error code [" + error + "]");
    }

    return null;
}

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

public static Object[] tagNodeWithEditText(HtmlCleaner cleaner, URL url, Handler handler, Context context,
        String fullTag, boolean login) throws IOException {
    Object[] ret = new Object[2];

    handler.sendEmptyMessage(PROGRESS_CONNECTING);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (login) {//from   ww  w .java 2s . com
        httpclient.setCookieStore(cookieStore);
    }
    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    InputStream is = response.getEntity().getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(context.openFileInput(TEMP_FILE_NAME)));
    ret[0] = TagNodeFromURLHelper(is, fullTag, handler, context, cleaner);
    ret[1] = parseTextArea(br);

    return ret;
}

From source file:com.github.ajasmin.telususageandroidwidget.TelusReportFetcher.java

private static void fetchUsageSummaryPage(DefaultHttpClient httpclient, PreferencesData prefs)
        throws NetworkErrorException {
    try {//from   w  w  w  .  j a v  a  2s. com
        final String url = "https://mobile.telus.com/index.htm";
        HttpPost httpPost = new HttpPost(url);

        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if (prefs.subscriber != null) {
            formparams.add(new BasicNameValuePair("subscriber", prefs.subscriber));
        }

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(entity);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();

        // Save the page to disk
        String fileName = Integer.toString(prefs.appWidgetId);
        FileOutputStream fileOutput = MyApp.getContext().openFileOutput(fileName, Context.MODE_PRIVATE);
        responseEntity.writeTo(fileOutput);
        fileOutput.close();
    } catch (IOException e) {
        throw new NetworkErrorException("Error fetching data from Telus website", e);
    }
}

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

public static Object[] parseEditText(HtmlCleaner cleaner, URL url, TLHandler handler, Context context)
        throws IOException {
    // Although probably not THE worst hack I've written, this function ranks near the top.
    // TODO: rework this routine get rid of code duplication.

    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);

    FileOutputStream fos = context.openFileOutput(TEMP_FILE_NAME, Context.MODE_PRIVATE);
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

    String line;/* ww  w .  ja  v a2 s . c  om*/
    String formStart = "<form action=\"/forum/edit.php";
    while ((line = br.readLine()) != null) {
        if (line.startsWith(formStart)) {
            Log.d(TAG, line);
            bw.write(line);
            break;
        }
    }

    String start = "\t\t<textarea";
    String end = "\t\t<p>";
    StringBuffer sb = new StringBuffer();
    while ((line = br.readLine()) != null) {
        if (line.startsWith(start)) {
            bw.write("</form>");
            int i = line.lastIndexOf('>');
            sb.append(Html.fromHtml(line.substring(i + 1)).toString());
            sb.append("\n");
            break;
        } else {
            bw.write(line);
        }
    }

    while ((line = br.readLine()) != null) {
        if (line.startsWith(end)) {
            break;
        }
        sb.append(Html.fromHtml(line).toString());
        sb.append("\n");
    }

    bw.flush();
    bw.close();

    if (handler != null)
        handler.sendEmptyMessage(PROGRESS_PARSING);

    Object[] ret = new Object[2];

    ret[0] = sb.toString();
    ret[1] = cleaner.clean(context.openFileInput(TEMP_FILE_NAME));
    return ret;
}

From source file:org.metasyntactic.utilities.ExceptionUtilities.java

/**
 * Look into the files folder to see if there are any "*.stacktrace" files. If
 * any are present, submit them to the trace server.
 *///from www  . j a v  a 2  s. co  m
public static void submitStackTraces() {
    try {
        String[] list = searchForStackTraces();
        if (list != null && list.length > 0) {
            for (int i = 0; i < list.length; i++) {
                File file = new File(FilesPath, list[i]);
                String version = list[i].split("-")[0];
                StringBuilder contents = new StringBuilder();
                BufferedReader input = new BufferedReader(new FileReader(file));
                String line = null;
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }
                input.close();
                String stacktrace;
                stacktrace = contents.toString();
                file.delete();

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(
                        "http://" + NowPlayingApplication.host + ".appspot.com/ReportCrash");
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair("name", Package));
                nvps.add(new BasicNameValuePair("version", version));
                nvps.add(new BasicNameValuePair("trace", stacktrace));
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

                httpClient.execute(httpPost);
            }
        }
    } catch (Exception e) {
    } finally {
        String[] list = searchForStackTraces();
        for (int i = 0; i < list.length; i++) {
            File file = new File(FilesPath, list[i]);
            file.delete();
        }
    }
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static void logout() throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.setCookieStore(cookieStore);

    HttpGet httpGet = new HttpGet(LOGOUT_URL + "?t=" + tokenField);

    try {/*from ww  w. j a  va  2 s. c  om*/
        httpclient.execute(httpGet);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    }

    loginStatus = false;
    cookieStore = null;
}

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

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

    try {/* w  w 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) {
            // 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:app.wz.HttpClient.java

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

    try {/*from  w  w w  .j  a va2s  . 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) {
            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;
}