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.example.montxu.magik_repair.HttpClient.java

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

    try {/*ww  w  . ja va 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;
}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

public static Response<?> postNoData(Context context, GHCredentials apiCredentials, String url,
        Map<String, String> headers) throws NoRouteToHostException, URISyntaxException, IOException,
        ClientProtocolException, AuthenticationException, UnsupportedEncodingException {
    if (!Utils.isInternetConnectionAvailable(context))
        throw new NoRouteToHostException("Network not available");

    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri, apiCredentials);

    HttpPost httpPost = new HttpPost(uri);

    setHeaders(httpPost, headers);/*from ww w  .  ja v a 2  s  . c  o  m*/

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPost);
    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

public static Response<String> deleteToURL(Context context, GHCredentials apiCredentials, String url,
        Map<String, String> headers) throws NoRouteToHostException, URISyntaxException, IOException,
        ClientProtocolException, AuthenticationException {
    if (!Utils.isInternetConnectionAvailable(context))
        throw new NoRouteToHostException("Network not available");

    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri, apiCredentials);

    HttpDelete httpPut = new HttpDelete(uri);

    setHeaders(httpPut, headers);// w  w  w  . j  a va  2 s .c  o m

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPut);

    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

private static Response<String> readInternetDataGet(Context context, GHCredentials apiCredentials, String url,
        Map<String, String> headers) throws NoRouteToHostException, URISyntaxException, IOException,
        ClientProtocolException, AuthenticationException, UnsupportedEncodingException {
    if (!Utils.isInternetConnectionAvailable(context))
        throw new NoRouteToHostException("Network not available");

    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri, apiCredentials);

    HttpGet httpGet = new HttpGet(uri);

    setHeaders(httpGet, headers);//from   ww w  . ja va2s  .co  m

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpGet);
    int code = httpResponse.getStatusLine().getStatusCode();

    parseResponseHeaders(context, httpResponse, ret);
    Log.d(TAG, "Response http code: " + code);
    if (code == HttpStatus.SC_NOT_MODIFIED) {
        ret.notModified = true;
        ret.snapRequestDuration();
        writeReponseInfo(ret, context);
        return ret;
    }
    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);
    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;

}

From source file:wordGame.Util.WebUtil.java

public static boolean SaveBoardToServer(Board board, String userID, String cubesID, String dictID)
        throws UnsupportedEncodingException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost postMethod = new HttpPost(WEBCREATEBOARD);
    String boardData = board.toWebString();
    List<NameValuePair> formParameters = new ArrayList<NameValuePair>();
    formParameters.add(new BasicNameValuePair("board_data", boardData));
    formParameters.add(new BasicNameValuePair("user_id", userID));
    formParameters.add(new BasicNameValuePair("cubes_id", cubesID));
    formParameters.add(new BasicNameValuePair("dictionary_id", dictID));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParameters, "UTF-8");
    postMethod.setEntity(entity);/* w  ww  .  j ava  2s . c o m*/
    try {
        HttpResponse response = httpclient.execute(postMethod);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            responseEntity.writeTo(System.out);
        }

        return true;
    } catch (IOException e) {
        return false;
    }

}

From source file:com.marklogic.client.functionaltest.JavaApiBatchSuite.java

public static void createRESTAppServer(String restServerName, int restPort) {
    try {//from w  w  w.  j av  a 2 s  . c o m
        DefaultHttpClient client = new DefaultHttpClient();

        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpPost post = new HttpPost("http://localhost:8002" + "/v1/rest-apis?format=json");
        String JSONString = "{ \"rest-api\": {\"name\":\"" + restServerName + "\",\"port\":\"" + restPort
                + "\"}}";
        //System.out.println(JSONString);      
        post.addHeader("Content-type", "application/json");
        post.setEntity(new StringEntity(JSONString));

        HttpResponse response = client.execute(post);
        HttpEntity respEntity = response.getEntity();

        if (respEntity != null) {
            // EntityUtils to get the response content
            String content = EntityUtils.toString(respEntity);
            System.out.println(content);
        }
    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();
    }
}

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

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

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

        // 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:com.optimusinfo.elasticpath.cortex.common.Utils.java

/**
 * This function performs the delete request
 * //  www  . j a  v  a2 s  .  c  o  m
 * @param deleteUrl
 * @param accessToken
 * @param contentType
 * @param contentTypeString
 * @param authorizationString
 * @param accessTokenInitializer
 * @return
 */
public static int deleteRequest(String deleteUrl, String accessToken, String contentType,
        String contentTypeString, String authorizationString, String accessTokenInitializer) {
    // Making HTTP request
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        Log.i("DELETE REQUEST", deleteUrl);
        HttpDelete httpDelete = new HttpDelete(deleteUrl);
        httpDelete.setHeader(contentTypeString, contentType);
        httpDelete.setHeader(authorizationString, accessTokenInitializer + " " + accessToken);
        HttpResponse httpResponse = httpClient.execute(httpDelete);
        return httpResponse.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}

From source file:com.pindroid.client.PinboardApi.java

/**
 * Performs an api call to Pinboard's http based api methods.
 * //from w  w w . java2 s  . c  o  m
 * @param url URL of the api method to call.
 * @param params Extra parameters included in the api call, as specified by different methods.
 * @param account The account being synced.
 * @param context The current application context.
 * @return A String containing the response from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 * @throws TooManyRequestsException 
 * @throws PinboardException 
 */
private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account,
        Context context)
        throws IOException, AuthenticationException, TooManyRequestsException, PinboardException {

    final AccountManager am = AccountManager.get(context);

    if (account == null)
        throw new AuthenticationException();

    final String username = account.name;
    String authtoken = "00000000000000000000"; // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401

    try {
        String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        if (tempAuthtoken != null)
            authtoken = tempAuthtoken;
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationException("Error getting auth token");
    }

    params.put("auth_token", username + ":" + authtoken);

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    String apiCallUrl = builder.build().toString();

    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);

    post.setHeader("User-Agent", "PinDroid");
    post.setHeader("Accept-Encoding", "gzip");

    final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    final HttpResponse resp = client.execute(post);

    final int statusCode = resp.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {

        final HttpEntity entity = resp.getEntity();

        InputStream instream = entity.getContent();

        final Header encoding = entity.getContentEncoding();

        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }

        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken);

        try {
            authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("Invalid auth token");
        }

        throw new AuthenticationException();
    } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) {
        throw new TooManyRequestsException(300);
    } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) {
        throw new PinboardException();
    } else {
        throw new IOException();
    }
}

From source file:imageLines.ImageHelpers.java

/**Read a jpeg image from a url into a BufferedImage*/

public static BufferedImage readAsBufferedImage(String imageURLString, String user, String pass) {
    InputStream i = null;//w w  w.jav a2 s  .  c om
    try {
        /*
        URLConnection conn=imageURL.openConnection();
        String userPassword=user+":"+ pass;
        String encoding = new sun.misc.BASE64Encoder().encode (userPassword.getBytes());
        conn.setRequestProperty ("Authorization", "Basic " + encoding);*/
        DefaultHttpClient httpclient = new DefaultHttpClient();

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY),
                new UsernamePasswordCredentials(user, pass));

        HttpGet httpget = new HttpGet(imageURLString);
        System.out.println("executing request" + httpget.getRequestLine());

        HttpResponse response = httpclient.execute(httpget);

        HttpEntity en = response.getEntity();
        Header[] h = response.getAllHeaders();
        for (int c = 0; c < h.length; c++)
            System.out.print(h[c].getName() + ":" + h[c].getValue() + "\n");

        i = response.getEntity().getContent();
        //JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(i);
        BufferedImage bi = ImageIO.read(i);//decoder.decodeAsBufferedImage();
        return bi;
    } catch (Exception e) {
        System.out.println(e);
        return null;
    } finally {
        try {
            if (i != null)
                i.close();
        } catch (IOException ex) {

        }
    }
}