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

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

Introduction

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

Prototype

void setHeader(String str, String str2);

Source Link

Usage

From source file:eu.prestoprime.plugin.mserve.client.MServeClient.java

private String pollJob(String jobID) throws MServeException {
    try {//from  w  w w. ja v  a 2  s. c  o m
        URL url = new URL(host + "/jobs/" + jobID);
        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpGet(url.toString());
        request.setHeader("Accept", "application/json");

        HttpEntity stream = client.execute(request).getEntity();
        InputStream istream = stream.getContent();

        BufferedReader buf = new BufferedReader(new InputStreamReader(istream));
        String output = "";
        String line;
        while (null != ((line = buf.readLine()))) {
            output += line.trim();
        }
        buf.close();
        istream.close();

        JSONObject response = new JSONObject(output);
        if (response.getJSONObject("tasks").getBoolean("failed"))
            throw new MServeException("Job failed...");
        if (!(response.getJSONObject("tasks").getBoolean("successful")))
            return null;
        return response.getJSONArray("joboutput_set").getJSONObject(0).getString("id");
    } catch (MalformedURLException e) {
        throw new MServeException("Bad REST interface...");
    } catch (IOException e) {
        throw new MServeException("Unable to make IO...");
    } catch (JSONException e) {
        throw new MServeException("Bad JSON response...");
    }
}

From source file:eu.prestoprime.plugin.mserve.client.MServeClient.java

private String createJob(String fileID, MServeTask task, Map<String, String> params) throws MServeException {
    try {//from ww  w  .j ava2s . co  m
        URL url = new URL(host + "/mfiles/" + fileID + "/jobs/");
        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpPost(url.toString());
        request.setHeader("Accept", "application/json");

        List<NameValuePair> parameters = new ArrayList<>();
        parameters.add(new BasicNameValuePair("jobtype", task.getName()));
        if (params != null)
            for (Entry<String, String> param : params.entrySet())
                parameters.add(new BasicNameValuePair(param.getKey(), param.getValue()));
        UrlEncodedFormEntity part = new UrlEncodedFormEntity(parameters);

        ((HttpPost) request).setEntity(part);

        HttpEntity stream = client.execute(request).getEntity();
        InputStream istream = stream.getContent();

        BufferedReader buf = new BufferedReader(new InputStreamReader(istream));
        String output = "";
        String line;
        while (null != ((line = buf.readLine()))) {
            output += line.trim();
        }
        buf.close();
        istream.close();

        JSONObject response = new JSONObject(output);
        System.out.println(response);
        return response.getString("id");
    } catch (MalformedURLException e) {
        throw new MServeException("Bad REST interface...");
    } catch (IOException e) {
        throw new MServeException("Unable to make IO...");
    } catch (JSONException e) {
        throw new MServeException("Bad JSON response...");
    }
}

From source file:eu.prestoprime.plugin.mserve.client.MServeClient.java

/**
 * Uploads a file on MServe and returns its fileID
 * //from   w w w.ja v  a2  s .c o  m
 * @param file
 * @return
 * @throws MServeException
 */
public String uploadFile(File file) throws MServeException {
    try {
        URL url = new URL(host + "/auths/" + serviceID + "/mfiles/");

        logger.debug("MServe URL: " + url.toString());

        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpPost(url.toString());
        request.setHeader("Accept", "application/json");

        MultipartEntity part = new MultipartEntity();
        part.addPart("file", new FileBody(file));

        ((HttpPost) request).setEntity(part);

        HttpEntity stream = client.execute(request).getEntity();
        InputStream istream = stream.getContent();

        BufferedReader buf = new BufferedReader(new InputStreamReader(istream));
        String line;
        StringBuffer sb = new StringBuffer();
        while (null != ((line = buf.readLine()))) {
            sb.append(line.trim());
        }
        buf.close();
        istream.close();

        logger.debug(sb.toString());

        JSONObject response = new JSONObject(sb.toString());

        return response.getString("id");
    } catch (MalformedURLException e) {
        throw new MServeException("Bad REST interface...");
    } catch (IOException e) {
        throw new MServeException("Unable to make IO...");
    } catch (JSONException e) {
        throw new MServeException("Bad JSON response...");
    }
}

From source file:com.mxhero.plugin.cloudstorage.onedrive.api.command.RefreshCommand.java

/**
 * Handler execute./*from   w w w  .ja va 2 s  .  c o m*/
 *
 * @param handler the handler
 * @return the t
 * @throws ApiException the api exception
 */
private T handlerExecute(CommandHandler<T> handler) throws ApiException {
    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;
    try {
        HttpUriRequest request = handler.request();
        request.setHeader("Authorization", "Bearer " + credential.getAccessToken());
        client = clientBuilder.build();
        response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new AuthenticationException("401 for " + credential.getUserId());
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND
                && response.getStatusLine().getStatusCode() > 399) {
            throw new ApiException(response);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND
                && response.getFirstHeader("WWW-Authenticate") != null
                && response.getFirstHeader("WWW-Authenticate").getValue() != null
                && response.getFirstHeader("WWW-Authenticate").getValue().contains("expired_token")) {
            throw new AuthenticationException("401 for " + credential.getUserId());
        }
        return handler.response(response);
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (Exception e) {
            }
            ;
        }
    }
}

From source file:org.eclipse.rcptt.internal.testrail.APIClient.java

private void setUpHeaders(HttpUriRequest request) {
    String credentials = username + ":" + password;
    String encodedCredentials = Base64.encode(credentials.getBytes(StandardCharsets.ISO_8859_1));
    String authorizationHeader = "Basic " + new String(encodedCredentials);
    request.setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);

    String contentTypeHeader = "application/json";
    request.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeHeader);
}

From source file:com.hp.mqm.clt.RestClient.java

private void addClientTypeHeader(HttpUriRequest request, boolean isLoginRequest) {
    request.setHeader("HPECLIENTTYPE", "HPE_CI_CLIENT");
    //        if (!isLoginRequest) {
    //            if (request.getFirstHeader(HPSSO_HEADER_NAME) == null) {
    //                request.setHeader(HPSSO_HEADER_NAME, CSRF_TOKEN.getValue());
    //            }
    //        }/*from   ww w .ja  v  a2  s  . co m*/
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java

@Test
public void testClassPathGet() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        final String lastModified;
        try (CloseableHttpResponse res = hc.execute(new HttpGet(newUri("/foo.txt")))) {
            lastModified = assert200Ok(res, "text/plain", "foo");
        }/*from ww  w. java2s. co  m*/

        // Test if the 'If-Modified-Since' header works as expected.
        HttpUriRequest req = new HttpGet(newUri("/foo.txt"));
        req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());
        req.setHeader(HttpHeaders.CONNECTION, "close");

        try (CloseableHttpResponse res = hc.execute(req)) {
            assert304NotModified(res, lastModified);
        }
    }
}

From source file:com.linecorp.armeria.server.http.file.HttpFileServiceTest.java

@Test
public void testUnknownMediaType() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal();
            CloseableHttpResponse res = hc.execute(new HttpGet(newUri("/bar.unknown")))) {
        final String lastModified = assert200Ok(res, null, "Unknown Media Type");

        HttpUriRequest req = new HttpGet(newUri("/bar.unknown"));
        req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate());
        req.setHeader(HttpHeaders.CONNECTION, "close");

        try (CloseableHttpResponse resCached = hc.execute(req)) {
            assert304NotModified(resCached, lastModified);
        }/*from   ww w . j a v  a 2 s . co  m*/
    }
}

From source file:de.damdi.fitness.activity.settings.sync.RestClient.java

/**
 * Sends the HTTP-request//from   ww w  .j a va 2  s  . c  om
 * 
 * @param request
 *            the request to send
 * @return the HTTP response
 * @throws IOException
 *             if HTTP status is NOT 'OK', 'CREATED' or 'ACCEPTED'
 */
protected HttpResponse execute(final HttpUriRequest request) throws IOException {
    request.setHeader(CONTENT_TYPE, MIMETYPE_JSON);

    HttpResponse resp = mClient.execute(request, mHttpContext);
    StatusLine status = resp.getStatusLine();
    switch (status.getStatusCode()) {
    case SC_OK:
    case SC_CREATED:
    case SC_ACCEPTED:
        return resp;
    case SC_UNPROCESSABLE_ENTITY:
        String json = readResponseBody(resp);
        throw new IOException(parseJsonError(json));
    default:
        String msg = status.getReasonPhrase() + " (" + status.getStatusCode() + ")";
        throw new IOException(msg + "\n" + readResponseBody(resp));
    }
}

From source file:org.droidparts.http.worker.HttpClientWorker.java

private HttpResponse getHttpResponse(HttpUriRequest req) throws HTTPException {
    for (String key : headers.keySet()) {
        for (String val : headers.get(key)) {
            req.addHeader(key, val);
        }/*w  w  w  .  j ava2 s .c o  m*/
    }
    req.setHeader("Accept-Encoding", "gzip,deflate");
    try {
        return httpClient.execute(req);
    } catch (Exception e) {
        throw new HTTPException(e);
    }
}