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.sepgil.ral.DrupalOperationTask.java

@Override
protected HttpResponse doInBackground(Endpoint... endpoints) {
    HttpResponse response = null;/*from  w w  w  .  j a  v  a2 s .  c o  m*/
    // If there is no Endpoint or we don't need to continue.
    if (endpoints.length == 0 && endpoints[0] == null) {
        onHttpError(null);
        return response;
    }
    // We only use the first endpoint, since we only want to perform the task on one site.
    Endpoint endpoint = endpoints[0];

    AndroidHttpClient client = AndroidHttpClient.newInstance("Android");

    // Request a new HTTPRequest and generate a path.
    HttpRequestBase request = getHttpRequest(endpoint.getUri() + getPath());
    // Add authentication and content type headers.
    request.setHeader("Authorization", "Basic " + endpoint.getAuth());
    request.setHeader("Content-Type", "application/json");
    request.setHeader("Accept", "application/json");

    try {
        // and try to execute the request.
        response = client.execute(request);
    } catch (IOException e) {
        onHttpError(null);
    }
    // AndroidHttpClient's need to be closed.
    client.close();
    return response;
}

From source file:v2.service.generic.library.utils.HttpClientUtil.java

public static HttpResponsePOJO jsonRequest(String url, String json, String requestType,
        Map<String, String> headers) throws Exception {
    HttpClient httpclient = createHttpClient();
    //        HttpEntityEnclosingRequestBase request=null;
    HttpRequestBase request = null;
    if ("POST".equalsIgnoreCase(requestType)) {
        request = new HttpPost(url);
    } else if ("PUT".equalsIgnoreCase(requestType)) {
        request = new HttpPut(url);
    } else if ("GET".equalsIgnoreCase(requestType)) {
        request = new HttpGet(url);
    } else if ("DELETE".equalsIgnoreCase(requestType)) {
        request = new HttpDelete(url);
    }// w  ww  .j  a  va2s  .c o  m
    if (json != null) {
        if (!"GET".equalsIgnoreCase(requestType) && (!"DELETE".equalsIgnoreCase(requestType))) {
            StringEntity params = new StringEntity(json, "UTF-8");
            params.setContentType("application/json;charset=UTF-8");
            ((HttpEntityEnclosingRequestBase) request).setEntity(params);
        }
    }
    if (headers == null) {
        request.addHeader("content-type", "application/json");
    } else {
        Set<String> keySet_header = headers.keySet();
        for (String key : keySet_header) {
            request.setHeader(key, headers.get(key));
        }
    }
    HttpResponsePOJO result = invoke(httpclient, request);
    return result;
}

From source file:com.flexive.rest.client.FxRestClient.java

private void setRequestParameters(HttpRequestBase request, String token) {
    if (StringUtils.isNotBlank(token)) {
        request.setHeader("token", token);
    }/*from   www.  j  a  va2  s .c  o m*/
}

From source file:com.pannous.es.reindex.MySearchResponseJson.java

private void addHeaders(HttpRequestBase http) {
    http.setHeader("Content-Type", "application/json; charset=utf-8");
    if (!credentials.isEmpty())
        http.setHeader("Authorization", "Basic " + credentials);
}

From source file:v2.service.generic.library.utils.HttpClientUtil.java

public static ResponsePOJO nativeRequest(String url, String json, String requestType,
        Map<String, String> headers) throws Exception {
    HttpClient httpclient = createHttpClient();
    //        HttpEntityEnclosingRequestBase request=null;
    HttpRequestBase request = null;
    if ("POST".equalsIgnoreCase(requestType)) {
        request = new HttpPost(url);
    } else if ("PUT".equalsIgnoreCase(requestType)) {
        request = new HttpPut(url);
    } else if ("GET".equalsIgnoreCase(requestType)) {
        request = new HttpGet(url);
    } else if ("DELETE".equalsIgnoreCase(requestType)) {
        request = new HttpDelete(url);
    }// w w w .j a v  a 2s . co m
    if (json != null) {
        if (!"GET".equalsIgnoreCase(requestType) && (!"DELETE".equalsIgnoreCase(requestType))) {
            StringEntity params = new StringEntity(json, "UTF-8");
            //                StringEntity s = new StringEntity(jsonString, "UTF-8");  
            ((HttpEntityEnclosingRequestBase) request).setEntity(params);
        }
    }
    if (headers == null) {
        request.addHeader("content-type", "application/json");
    } else {
        Set<String> keySet_header = headers.keySet();
        for (String key : keySet_header) {
            request.setHeader(key, headers.get(key));
        }
    }
    ResponsePOJO result = nativeInvoke(httpclient, request);
    return result;
}

From source file:com.magnet.plugin.api.requests.abs.BaseRequest.java

@Override
public void doWork() {
    try {// w  w  w  . jav a  2s.  c o  m
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpRequestBase request = getRequest(requestModel);

        List<RequestHeaderModel> requestModelHeaders = requestModel.getHeaders();

        for (RequestHeaderModel header : requestModelHeaders) {
            request.setHeader(header.getName(), header.getValue());
        }

        // If not specified as a header argument, Content-Type is inferred from the request body
        // Add the header here so the request is successful.
        if (request.getHeaders(ContentTypeHelper.CONTENT_TYPE_HEADER) == null
                || request.getHeaders(ContentTypeHelper.CONTENT_TYPE_HEADER).length == 0) {
            RestContentType type = ExampleParser.guessContentType(requestModel.getRequest());
            if (null != type) {
                request.setHeader(ContentTypeHelper.CONTENT_TYPE_HEADER, type.getName());
            }
        }
        // check if content-type is parameterized
        HttpResponse httpResponse = httpClient.execute(request);
        ApiMethodModel methodModel = new ApiMethodModel();
        methodModel.setRequestHeaders(request.getAllHeaders());
        methodModel.setHttpResponse(httpResponse);
        methodModel.setRequestModel(requestModel);
        onSuccess(methodModel);
    } catch (Exception e) {
        e.printStackTrace();
        Logger.info(getClass(), e.toString());
        onError(e);
    }

}

From source file:com.yahoo.sql4d.sql4ddriver.DruidNodeAccessor.java

private void addHeaders(HttpRequestBase req, Map<String, String> reqHeaders) {
    if (reqHeaders == null)
        return;/*  w  ww  .  j  a  v a  2  s  .c o  m*/
    for (String key : reqHeaders.keySet()) {
        req.setHeader(key, reqHeaders.get(key));
    }
}

From source file:org.eclipse.mylyn.internal.bugzilla.rest.core.BugzillaRestAuthenticatedGetRequest.java

@Override
protected void authenticate(IOperationMonitor monitor) throws IOException {
    UserCredentials credentials = getClient().getLocation().getCredentials(AuthenticationType.REPOSITORY);
    if (credentials == null) {
        throw new IllegalStateException("Authentication requested without valid credentials");
    }// ww w .j a  va2  s .  c  o m
    HttpRequestBase request = new HttpGet(baseUrl() + MessageFormat.format("/login?login={0}&password={1}",
            new Object[] { credentials.getUserName(), credentials.getPassword() }));
    request.setHeader(CONTENT_TYPE, TEXT_XML_CHARSET_UTF_8);
    request.setHeader(ACCEPT, APPLICATION_JSON);
    HttpResponse response = getClient().execute(request, monitor);
    try {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            getClient().setAuthenticated(false);
            throw new AuthenticationException("Authentication failed",
                    new AuthenticationRequest<AuthenticationType<UserCredentials>>(getClient().getLocation(),
                            AuthenticationType.REPOSITORY));
        } else {
            TypeToken<LoginToken> type = new TypeToken<LoginToken>() {
            };
            InputStream is = response.getEntity().getContent();
            InputStreamReader in = new InputStreamReader(is);
            LoginToken loginToken = new Gson().fromJson(in, type.getType());
            ((BugzillaRestHttpClient) getClient()).setLoginToken(loginToken);
            getClient().setAuthenticated(true);
        }
    } finally {
        HttpUtil.release(request, response, monitor);
    }
}

From source file:org.jfrog.build.client.ArtifactoryDependenciesClient.java

private HttpResponse execute(String artifactUrl, boolean isHead) throws IOException {
    PreemptiveHttpClient client = httpClient.getHttpClient();

    artifactUrl = ArtifactoryHttpClient.encodeUrl(artifactUrl);
    HttpRequestBase httpRequest = isHead ? new HttpHead(artifactUrl) : new HttpGet(artifactUrl);

    //Explicitly force keep alive
    httpRequest.setHeader("Connection", "Keep-Alive");
    HttpResponse response = client.execute(httpRequest);
    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == HttpStatus.SC_NOT_FOUND) {
        EntityUtils.consume(response.getEntity());
        throw new FileNotFoundException("Unable to find " + artifactUrl);
    }//from  www.  j  a v a 2  s .  co m

    if (statusCode != HttpStatus.SC_OK) {
        EntityUtils.consume(response.getEntity());
        throw new IOException("Error downloading " + artifactUrl + ". Code: " + statusCode + " Message: "
                + statusLine.getReasonPhrase());
    }
    return response;
}

From source file:com.eTilbudsavis.etasdk.network.impl.DefaultHttpNetwork.java

private void setHeaders(Request<?> request, HttpRequestBase http) {
    HashMap<String, String> headers = new HashMap<String, String>(request.getHeaders().size());
    headers.putAll(request.getHeaders());
    for (String key : headers.keySet())
        http.setHeader(key, headers.get(key));
}