Example usage for org.apache.http.client.methods HttpRequestBase setHeader

List of usage examples for org.apache.http.client.methods HttpRequestBase setHeader

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase setHeader.

Prototype

public void setHeader(String str, String str2) 

Source Link

Usage

From source file:com.youzu.android.framework.http.HttpHandler.java

@SuppressWarnings("unchecked")
private ResponseInfo<T> sendRequest(HttpRequestBase request) throws HttpException {

    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {

        if (autoResume && isDownloadingFile) {
            File downloadFile = new File(fileSavePath);
            long fileLen = 0;
            if (downloadFile.isFile() && downloadFile.exists()) {
                fileLen = downloadFile.length();
            }//from   w ww .j  a v  a2s.  c  om
            if (fileLen > 0) {
                request.setHeader("RANGE", "bytes=" + fileLen + "-");
            }
        }

        boolean retry = true;
        IOException exception = null;
        try {
            //                ResponseInfo<T> responseInfo = null;
            //                if (!isCancelled()) {
            //                    HttpResponse response = client.execute(request, context);
            //                    responseInfo = handleResponse(response);
            ////                    CookieStore store = client.getCookieStore();
            //                }
            //                return responseInfo;

            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseInfo<T>(null, (T) result, true);
                }
            }
            ResponseInfo<T> responseInfo = null;
            if (!isCancelled()) {
                HttpResponse response = client.execute(request, context);
                responseInfo = handleResponse(response);
            }
            return responseInfo;
        } catch (UnknownHostException e) {
            Log.e("APP", "HttpHandler sendRequest UnknownHostException:" + e.getMessage());

            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (IOException e) {
            Log.e("APP", "HttpHandler sendRequest IOException: " + e.toString());

            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (NullPointerException e) {
            Log.e("APP", "HttpHandler sendRequest NullPointerException:" + e.getMessage());

            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        } catch (HttpException e) {
            Log.e("APP", "HttpHandler sendRequest HttpException:" + e.getMessage());

            throw e;
        } catch (Throwable e) {
            Log.e("APP", "HttpHandler sendRequest Throwable:" + e.getMessage());

            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedCount, context);
        }

        Log.e("APP", "retry:" + retry);

        if (!retry) {
            HttpException httpException = new HttpException(exception);
            Log.e("APP", "HttpHandler sendRequest HttpException:" + httpException.getMessage());
            //                callback.onFailure(httpException,httpException.getMessage());
            throw httpException;
        }
    }
}

From source file:helper.util.RESTClient.java

/**
 * Main method for server request. Depending on call status, the callback methods are
 * invoked.//  w w w  .jav  a2s  . c  om
 * @param URI full address from which we need to get response.
 */
@Override
protected Void doInBackground(URI... uris) {
    if (!networkAvailable()) {
        System.out.println("no network connection");
        _handler.onFailure(FailStatus.NoNetworkConnection);
        return null;
    }

    HttpClient httpclient = new DefaultHttpClient();
    final HttpParams httpParameters = httpclient.getParams();

    int connectionTimeOutSec = 10;
    HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000);
    int socketTimeoutSec = 10;
    HttpConnectionParams.setSoTimeout(httpParameters, socketTimeoutSec * 1000);

    HttpRequestBase httpRequest = null;
    if (_methodType == "GET") {
        // check if we have any params
        if (_params != null) {
            String paramString = URLEncodedUtils.format(_params, "utf-8");
            httpRequest = new HttpGet(uris[0] + "?" + paramString);
            Log.d("request", uris[0] + "?" + paramString);
        } else {
            httpRequest = new HttpGet(uris[0]);
            Log.d("request", uris[0].toString());
        }
    } else {
        httpRequest = new HttpPost(uris[0]);
        if (_params != null) {
            Log.d("request", uris[0].toString());
            addPostParameters(httpRequest);
        }
    }
    httpRequest.setHeader("Accept", "application/json");
    httpRequest.setHeader("Content-Type", "application/json");
    try {
        // start http request
        HttpResponse response = httpclient.execute(httpRequest);
        // get response string
        String responseData = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);

        // determine response type(json array or object)
        Object json = null;
        try {
            json = new JSONTokener(responseData).nextValue();
            _handler.onSuccess(json);
        } catch (JSONException e) {
            _handler.onFailure(FailStatus.JSONException);
        }
    } catch (ClientProtocolException e) {
        System.out.println("AsyncTask:GetUserDataThread:ClientProtocolException: " + e.getMessage());
        _handler.onFailure(FailStatus.ClientProtocolException);
    } catch (IOException e) {
        System.out.println("AsyncTask:GetUserDataThread:IOException: " + e.getMessage());
        _handler.onFailure(FailStatus.IOException);
    }

    return null;
}

From source file:org.ballerinalang.composer.service.tryit.service.HttpTryItClient.java

/**
 * {@inheritDoc}//  w  ww .  j av  a  2s. co  m
 */
@Override
public String execute() throws TryItException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpCoreContext localContext = new HttpCoreContext();
        // Create url for the request.
        String requestUrl = this.buildUrl();
        String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString();
        switch (httpMethod.toLowerCase(Locale.getDefault())) {
        case "get":
        case "delete":
        case "options":
        case "head":
        case "trace":
            HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString());
                }
            }

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long start = System.currentTimeMillis();

            // Executing the request.
            HttpResponse response = client.execute(httpRequest, localContext);
            long elapsed = System.currentTimeMillis() - start;

            return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl,
                    elapsed);
        default:
            HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase(
                    httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpEntityRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getEntityHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpEntityRequest.setHeader(header.get("key").getAsString(),
                            header.get("value").getAsString());
                }
            }

            // Setting the body of the request.
            StringEntity postEntity = new StringEntity(
                    this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString());
            httpEntityRequest.setEntity(postEntity);

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long entityRequestStart = System.currentTimeMillis();

            // Executing the request.
            HttpResponse entityResponse = client.execute(httpEntityRequest, localContext);
            long entityRequestDuration = System.currentTimeMillis() - entityRequestStart;
            return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl,
                    entityRequestDuration);
        }
    } catch (IOException e) {
        throw new TryItException(e.getMessage());
    }
}

From source file:org.ballerinalang.composer.service.workspace.tryit.HttpTryItClient.java

/**
 * {@inheritDoc}/*from  w w  w  . j a  va2 s.  c  o  m*/
 */
@Override
public String execute() throws TryItException {
    try {
        HttpClient client = HttpClientBuilder.create().build();
        HttpCoreContext localContext = new HttpCoreContext();
        // Create url for the request.
        String requestUrl = this.buildUrl();
        String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString();
        switch (httpMethod.toLowerCase(Locale.getDefault())) {
        case "get":
        case "delete":
        case "options":
        case "head":
        case "trace":
            HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString());
                }
            }

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long start = System.currentTimeMillis();

            // Executing the request.
            HttpResponse response = client.execute(httpRequest, localContext);
            long elapsed = System.currentTimeMillis() - start;

            return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl,
                    elapsed);
        default:
            HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase(
                    httpMethod.toUpperCase(Locale.getDefault()));

            // Setting the url for the request.
            httpEntityRequest.setURI(URI.create(requestUrl));

            // Setting the request headers.
            JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS);
            for (JsonElement getHeader : getEntityHeaders) {
                JsonObject header = getHeader.getAsJsonObject();
                if (StringUtils.isNotBlank(header.get("key").getAsString())
                        && StringUtils.isNotBlank(header.get("value").getAsString())) {
                    httpEntityRequest.setHeader(header.get("key").getAsString(),
                            header.get("value").getAsString());
                }
            }

            // Setting the body of the request.
            StringEntity postEntity = new StringEntity(
                    this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString());
            httpEntityRequest.setEntity(postEntity);

            // Setting the content type.
            if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType());
            } else {
                httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE,
                        this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString());
            }

            // To track how long the request took.
            long entityRequestStart = System.currentTimeMillis();

            // Executing the request.
            HttpResponse entityResponse = client.execute(httpEntityRequest, localContext);
            long entityRequestDuration = System.currentTimeMillis() - entityRequestStart;
            return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl,
                    entityRequestDuration);
        }
    } catch (java.io.IOException e) {
        throw new TryItException(e.getMessage());
    }
}

From source file:synapticloop.scaleway.api.ScalewayApiClient.java

/**
 * Execute the request, returning the parsed response object
 *
 * @param httpMethod          The HTTP method to execute (GET/POST/PATCH/DELETE/PUT)
 * @param url                 The URL to hit
 * @param path                the path to request
 * @param allowableStatusCode the allowable return HTTP status code
 * @param returnClass         the return class type
 * @return The returned and parsed response
 * @throws ScalewayApiException If there was an error calling the api
 *///from   w w w .  j a  v a 2s  .c  o  m
private <T> T execute(String httpMethod, String url, String path, int allowableStatusCode, Class<T> returnClass)
        throws ScalewayApiException {
    String requestPath = new StringBuilder(url).append(path).toString();

    HttpRequestBase request = buildRequest(httpMethod, requestPath);

    request.setHeader(Constants.HEADER_KEY_AUTH_TOKEN, accessToken);
    request.setHeader(HttpHeaders.CONTENT_TYPE, Constants.HEADER_VALUE_JSON_APPLICATION);

    HttpResponse response;
    try {
        LOGGER.debug("Executing '{}' for url '{}'", httpMethod, requestPath);
        response = httpclient.execute(request);
    } catch (IOException ex) {
        throw new ScalewayApiException(ex);
    }

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

    if (statusCode == allowableStatusCode) {
        LOGGER.debug("Status code received: {}, wanted: {}.", statusCode, allowableStatusCode);
        if (null != returnClass) {
            return parseResponse(response, returnClass);
        } else {
            return (null);
        }
    } else {
        LOGGER.error("Invalid status code received: {}, wanted: {}.", statusCode, allowableStatusCode);
        try {
            throw new ScalewayApiException(IOUtils.toString(response.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException ex) {
            throw new ScalewayApiException(ex);
        }
    }
}

From source file:net.dahanne.gallery3.client.business.G3Client.java

private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs,
        String requestMethod, File file)
        throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException {
    HttpClient defaultHttpClient = new DefaultHttpClient();
    HttpRequestBase httpMethod;// www . ja  v  a2s .  c  om
    //are we using rewritten urls ?
    if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) {
        appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php");
    }

    logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl);
    if (POST.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        if (file != null) {
            MultipartEntity multipartEntity = new MultipartEntity();

            String string = nameValuePairs.toString();
            // dirty fix to remove the enclosing entity{}
            String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1);

            StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8"));
            multipartEntity.addPart("entity", contentBody);
            FileBody fileBody = new FileBody(file);
            multipartEntity.addPart("file", fileBody);
            ((HttpPost) httpMethod).setEntity(multipartEntity);
        } else {
            ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
    } else if (PUT.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } else if (DELETE.equals(requestMethod)) {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //this is to avoid the HTTP 414 (length too long) error
        //it should only happen when getting items, index.php/rest/items?urls=
        //      } else if(appendToGalleryUrl.length()>2000) {
        //         String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?"));
        //         String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("="));
        //         String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1);
        //         httpMethod = new HttpPost(galleryItemUrl + resource);
        //         httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //         nameValuePairs.add(new BasicNameValuePair(variable, value));
        //         ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(
        //               nameValuePairs));
    } else {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
    }
    if (existingApiKey != null) {
        httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey);
    }
    //adding the userAgent to the request
    httpMethod.setHeader(USER_AGENT, userAgent);
    HttpResponse response = null;

    String[] patternsArray = new String[3];
    patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z";
    patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z";
    patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z";
    try {
        // be extremely careful here, android httpclient needs it to be
        // an
        // array of string, not an arraylist
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray);
        response = defaultHttpClient.execute(httpMethod);
    } catch (ClassCastException e) {
        List<String> patternsList = Arrays.asList(patternsArray);
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList);
        response = defaultHttpClient.execute(httpMethod);
    }

    int responseStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = null;
    if (response.getEntity() != null) {
        responseEntity = response.getEntity();
    }

    switch (responseStatusCode) {
    case HttpURLConnection.HTTP_CREATED:
        break;
    case HttpURLConnection.HTTP_OK:
        break;
    case HttpURLConnection.HTTP_MOVED_TEMP:
        //the gallery is using rewritten urls, let's remember it and re hit the server
        this.isUsingRewrittenUrls = true;
        responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
        break;
    case HttpURLConnection.HTTP_BAD_REQUEST:
        throw new G3BadRequestException();
    case HttpURLConnection.HTTP_FORBIDDEN:
        //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url
        if (appendToGalleryUrl.contains(INDEX_PHP_REST)) {
            this.isUsingRewrittenUrls = true;
            responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
            break;
        }
        throw new G3ForbiddenException();
    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new G3ItemNotFoundException();
    default:
        throw new G3GalleryException("HTTP code " + responseStatusCode);
    }

    return responseEntity;
}

From source file:com.flipkart.phantom.http.impl.HttpConnectionPool.java

/**
 * This method sets the headers to the http request base. This implementation adds the custom headers configured on this pool and subsequently adds
 * the headers that came with the specified Http request if {@link HttpConnectionPool#isForwardHeaders()} is set to 'true' and in this case sets the
 * {@link HTTP#TARGET_HOST} to the the value <HttpConnectionPool{@link #getHost()}:HttpConnectionPool{@link #getPort()}. Sub-types may override this method
 * to change this behavior.//from   w w  w .j ava 2 s. c  o m
 *
 * @param request {@link HttpRequestBase} to add headers to.
 * @param requestHeaders the List of header tuples which are added to the request
 */
protected void setRequestHeaders(HttpRequestBase request, List<Map.Entry<String, String>> requestHeaders) {
    if (this.headers != null && this.headers.isEmpty()) {
        for (String headerKey : this.headers.keySet()) {
            request.addHeader(headerKey, this.headers.get(headerKey));
        }
    }
    if (this.isForwardHeaders()) { // forward request headers only if specified

        if (requestHeaders != null && !requestHeaders.isEmpty()) {
            for (Map.Entry<String, String> headerMap : requestHeaders) {
                if (!HttpConnectionPool.REMOVE_HEADERS.contains(headerMap.getKey())) {
                    request.addHeader(headerMap.getKey(), headerMap.getValue());
                }
            }
        }
        // replace "Host" header with the that of the real target host
        request.setHeader(HTTP.TARGET_HOST, this.getHost() + ":" + this.getPort());
    }
}

From source file:com.blazemeter.bamboo.plugin.api.HttpUtility.java

public <V> HttpResponse httpResponse(String url, V data, Method method) throws IOException {
    if (StringUtils.isBlank(url))
        return null;
    logger.info("Requesting : " + url.substring(0, url.indexOf("?") + 14));
    HttpResponse response = null;/*  ww  w  . j  a v  a 2  s . co  m*/
    HttpRequestBase request = null;

    try {
        if (method == Method.GET) {
            request = new HttpGet(url);
        } else if (method == Method.POST) {
            request = new HttpPost(url);
            if (data != null) {
                ((HttpPost) request).setEntity(new StringEntity(data.toString()));
            }
        } else if (method == Method.PUT) {
            request = new HttpPut(url);
            if (data != null) {
                ((HttpPut) request).setEntity(new StringEntity(data.toString()));
            }
        } else if (method == Method.PATCH) {
            request = new HttpPatch(url);
            if (data != null) {
                ((HttpPatch) request).setEntity(new StringEntity(data.toString()));
            }
        } else {
            throw new RuntimeException("Unsupported method: " + method.toString());
        }
        request.setHeader("Accept", "application/json");
        request.setHeader("Content-type", "application/json; charset=UTF-8");
        if (proxy != null) {
            RequestConfig conf = RequestConfig.custom().setProxy(proxy).build();
            request.setConfig(conf);
        }
        response = this.httpClient.execute(request);

        if (response == null || response.getStatusLine() == null) {
            logger.info("Erroneous response (Probably null) for url: \n" + url);
            response = null;
        }
    } catch (Exception e) {
        logger.error("Problems with creating and sending request: \n", e);
    }
    return response;
}

From source file:com.k42b3.neodym.oauth.Oauth.java

@SuppressWarnings("unused")
private HttpEntity httpRequest(String method, String url, Map<String, String> header, String body)
        throws Exception {
    // build request
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 6000);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

    HttpRequestBase request;

    if (method.equals("GET")) {
        request = new HttpGet(url);
    } else if (method.equals("POST")) {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("text", new StringBody(body));

        request = new HttpPost(url);

        ((HttpPost) request).setEntity(entity);
    } else {//from ww  w.j  a v  a 2s  .c  o m
        throw new Exception("Invalid request method");
    }

    // header
    Set<String> keys = header.keySet();

    for (String key : keys) {
        request.setHeader(key, header.get(key));
    }

    // execute HTTP Get Request
    logger.info("Request: " + request.getRequestLine());

    HttpResponse httpResponse = httpClient.execute(request);

    HttpEntity entity = httpResponse.getEntity();

    String responseContent = EntityUtils.toString(entity);

    // log traffic
    if (trafficListener != null) {
        TrafficItem trafficItem = new TrafficItem();

        trafficItem.setRequest(request);
        trafficItem.setResponse(httpResponse);
        trafficItem.setResponseContent(responseContent);

        trafficListener.handleRequest(trafficItem);
    }

    // check status code
    int statusCode = httpResponse.getStatusLine().getStatusCode();

    if (!(statusCode >= 200 && statusCode < 300)) {
        JOptionPane.showMessageDialog(null, responseContent);

        throw new Exception("No successful status code");
    }

    return entity;
}