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:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ??????????????????./*from w w w .j  a v a2s  . co m*/
 */
@Test
public final void nonSupportedResponseHeader() {
    String url;
    String testSrc = "nonSupportedResponseHeader.js";

    HttpUriRequest req = null;
    try {
        if (isServiceTest) {
            // ? Dav?put
            putScript(testSrc, "test.js");
            url = requestUrl();
        } else {
            url = requestUrl(testSrc);
        }
        // ?
        req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
        req.setHeader(KEY_HEADER_BASEURL, baseUrl);
        String version = getVersion();
        if (version != null && !(version.equals(""))) {
            req.setHeader("X-Personium-Version", version);
        }

        HttpResponse objResponse;
        objResponse = httpClient.execute(req);
        PersoniumResponse dcRes = new PersoniumResponse(objResponse);

        assertEquals(200, dcRes.getStatusCode());
        assertEquals("header value", dcRes.getHeader("Invalid-custom-header"));
        assertEquals("??", dcRes.bodyAsString());

    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}

From source file:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ?Transfer-Encoding????????./*from   ww  w. j a  v a  2 s  . c  om*/
 */
@Test
public final void nonSupportedResponseHeaderTransferEncoding() {
    String url;
    String testSrc = "nonSupportedResponseHeaderTransferEncoding.js";

    HttpUriRequest req = null;
    try {
        if (isServiceTest) {
            // ? Dav?put
            putScript(testSrc, "test.js");
            url = requestUrl();
        } else {
            url = requestUrl(testSrc);
        }
        // ?
        req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
        req.setHeader(KEY_HEADER_BASEURL, baseUrl);
        String version = getVersion();
        if (version != null && !(version.equals(""))) {
            req.setHeader("X-Personium-Version", version);
        }

        HttpResponse objResponse;
        objResponse = httpClient.execute(req);
        PersoniumResponse dcRes = new PersoniumResponse(objResponse);

        assertEquals(200, dcRes.getStatusCode());
        assertEquals("", dcRes.getHeader("Transfer-Encoding"));
        assertEquals("??", dcRes.bodyAsString());

    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}

From source file:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ?Content-type???????????????./* w w  w .j ava 2  s  .  co m*/
 */
@Test
public final void unmatchedBodyAndContentType() {
    String url;
    String testSrc = "unmatchedBodyAndContentType.js";

    HttpUriRequest req = null;
    try {
        if (isServiceTest) {
            // ? Dav?put
            putScript(testSrc, "test.js");
            url = requestUrl();
        } else {
            url = requestUrl(testSrc);
        }
        // ?
        req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
        req.setHeader(KEY_HEADER_BASEURL, baseUrl);
        String version = getVersion();
        if (version != null && !(version.equals(""))) {
            req.setHeader("X-Personium-Version", version);
        }

        HttpResponse objResponse;
        objResponse = httpClient.execute(req);
        PersoniumResponse dcRes = new PersoniumResponse(objResponse);

        String bodyAsString = dcRes.bodyAsString();
        assertEquals(200, dcRes.getStatusCode());
        assertEquals("??", bodyAsString);

    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}

From source file:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ????Service.//from  w  ww.  j a v  a 2 s. com
 */
@Test
public final void serviceEmpty() {
    String url;
    HttpUriRequest req = null;
    try {
        if (isServiceTest) {
            // ? Dav?put
            putScript("empty.js", "test.js");
            url = requestUrl();
        } else {
            url = requestUrl("empty.js");
        }
        // ?
        req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
        req.setHeader(KEY_HEADER_BASEURL, baseUrl);
        String version = getVersion();
        if (version != null && !(version.equals(""))) {
            req.setHeader("X-Personium-Version", version);
        }

        HttpResponse objResponse;
        objResponse = httpClient.execute(req);
        PersoniumResponse dcRes = new PersoniumResponse(objResponse);

        // ???Content-Lengh ???????
        int statusCode = objResponse.getStatusLine().getStatusCode();
        assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, statusCode);
        String contentLength = dcRes.getHeader(HttpHeaders.CONTENT_LENGTH);
        if (contentLength == null || contentLength.length() <= 0) {
            fail("Content-Lengh header value does not exist");
        }
    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}

From source file:org.fedoraproject.copr.client.impl.RpcCommand.java

public T execute(DefaultCoprSession session) throws CoprException {
    try {/*from www  . j a  v  a 2s  . c o  m*/
        HttpClient client = session.getClient();

        String baseUrl = session.getConfiguration().getUrl();
        String commandUrl = getCommandUrl();
        String url = baseUrl + commandUrl;

        Map<String, String> extraArgs = getExtraArguments();
        HttpUriRequest request;
        if (extraArgs == null) {
            request = new HttpGet(url);
        } else {
            HttpPost post = new HttpPost(url);
            request = post;

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            for (Entry<String, String> entry : extraArgs.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }

        if (requiresAuthentication()) {
            String login = session.getConfiguration().getLogin();
            if (login == null || login.isEmpty())
                throw new CoprException("Authentification is required to perform this command "
                        + "but no login was provided in configuration");

            String token = session.getConfiguration().getToken();
            if (token == null || token.isEmpty())
                throw new CoprException("Authentification is required to perform this command "
                        + "but no login was provided in configuration");

            String auth = login + ":" + token;
            String encodedAuth = DatatypeConverter.printBase64Binary(auth.getBytes(StandardCharsets.UTF_8));
            request.setHeader("Authorization", "Basic " + encodedAuth);
        }

        request.addHeader("Accept", APPLICATION_JSON.getMimeType());

        HttpResponse response = client.execute(request);
        int returnCode = response.getStatusLine().getStatusCode();

        if (returnCode != HttpURLConnection.HTTP_OK) {
            throw new CoprException(
                    "Copr RPC failed: HTTP " + returnCode + " " + response.getStatusLine().getReasonPhrase());
        }

        Reader responseReader = new InputStreamReader(response.getEntity().getContent());
        JsonParser parser = new JsonParser();
        JsonObject rpcResponse = parser.parse(responseReader).getAsJsonObject();

        String rpcStatus = rpcResponse.get("output").getAsString();
        if (!rpcStatus.equals("ok")) {
            throw new CoprException("Copr RPC returned failure reponse");
        }

        return parseResponse(rpcResponse);
    } catch (IOException e) {
        throw new CoprException("Failed to call remote Copr procedure", e);
    }
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

protected void setHeaders(HttpUriRequest method) {
    HttpMethodConfiguration config = httpConfiguration == null ? null
            : httpConfiguration.getMethodConfiguration(method);
    if (config == null || config.isUseDefaultHeaders()) {
        // TODO: merge with the other headers and have some better defaults, unify with lightweight headers
        method.addHeader("Cache-control", "no-cache");
        method.addHeader("Cache-store", "no-store");
        method.addHeader("Pragma", "no-cache");
        method.addHeader("Expires", "0");
        method.addHeader("Accept-Encoding", "gzip");
    }/*ww w .j  a v a 2  s . c om*/

    if (httpHeaders != null) {
        for (Map.Entry<Object, Object> entry : httpHeaders.entrySet()) {
            method.setHeader((String) entry.getKey(), (String) entry.getValue());
        }
    }

    Header[] headers = config == null ? null : config.asRequestHeaders();
    if (headers != null) {
        for (Header header : headers) {
            method.setHeader(header);
        }
    }
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

@Override
protected Response sendVideoUploadRequest(URL url, RequestMethod method, String auth, InputStream input,
        String fileName, final long fileSize) throws IOException, OAuthException {
    if (method == null)
        method = RequestMethod.POST;//from ww w. j  ava 2  s .  c o m
    if (!RequestMethod.POST.equals(method) && !RequestMethod.PUT.equals(method))
        throw new IllegalArgumentException("Invalid request method!");

    HttpUriRequest request = null;
    if (RequestMethod.POST.equals(method)) {
        request = new HttpPost(url.toString());
    } else if (RequestMethod.PUT.equals(method)) {
        request = new HttpPut(url.toString());
    } else {
        throw new IOException("Unsupported request method '" + method + "'!");
    }

    MultipartEntityBuilder b = MultipartEntityBuilder.create();

    // add auth part to the multipart entity
    auth = StringUtils.trimToNull(auth);
    if (auth != null) {
        //StringBody authPart = new StringBody(
        //  auth, ContentType.create( "text/plain", getEncoding() ) );
        //b.addPart( "auth", authPart );
        b.addTextBody("auth", auth, ContentType.create("text/plain", getEncoding()));
    }

    // add file part to the multipart entity
    if (input != null) {
        fileName = StringUtils.trimToNull(fileName);
        if (fileName == null)
            fileName = "upload.bin";
        //InputStreamBody filePart = new InputStreamBody( input, fileName );
        InputStreamBody filePart = new InputStreamBodyWithLength(input, fileName, fileSize);
        b.addPart("videofile", filePart);
    }

    // add multipart entity to the request
    HttpEntity requestMultipartEntity = b.build();
    request.setHeader("MIME-Version", "1.0");
    request.addHeader(requestMultipartEntity.getContentType());
    request.setHeader("Content-Language", "en-US");
    request.setHeader("Accept-Charset", "UTF-8");
    request.setHeader("Accept-Encoding", "gzip,deflate");
    request.setHeader("Connection", "close");
    ((HttpEntityEnclosingRequest) request).setEntity(requestMultipartEntity);

    // sign request
    //getAuthConsumer().sign( request );

    // send request
    HttpResponse response = httpClient.execute(request);

    // create response
    return createResponse(response);
}

From source file:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ???????????HTTP????????.//from  w w  w .  ja v a 2 s.  c o m
 */
@Test
public final void nonSupportedResponseCode() {
    String url;
    HttpUriRequest req = null;
    try {
        String[][] jsList = {{"nonSupportedResponseCode105.js", "105" },
                {"nonSupportedResponseCode301.js", "301" },
                {"nonSupportedResponseCode303.js", "303" }, {"nonSupportedResponseCode307.js", "307" } };
        for (String[] testSrc : jsList) {
            // ? Dav?put
            if (isServiceTest) {
                putScript(testSrc[0], "test.js");
                url = requestUrl();
            } else {
                url = requestUrl(testSrc[0]);
            }
            // ?
            req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
            req.setHeader(KEY_HEADER_BASEURL, baseUrl);
            String version = getVersion();
            if (version != null && !(version.equals(""))) {
                req.setHeader("X-Personium-Version", version);
            }
            // ???
            HttpResponse objResponse = httpClient.execute(req);
            PersoniumResponse dcRes = new PersoniumResponse(objResponse);
            assertEquals(500, dcRes.getStatusCode());
            String expectedMessage = String.format("Server Error : response status illegal type. status: %s",
                    testSrc[1]);
            assertEquals(expectedMessage, dcRes.bodyAsString());
            EntityUtils.consume(objResponse.getEntity());
        }
    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}

From source file:io.personium.jersey.engine.test.ScriptTest.java

/**
 * ???????????HTTP????????(???)./*w w w  .ja  v a2 s. c  o m*/
 */
@Test
public final void nonSupportedResponseCodeWithQuery() {
    String url;
    HttpUriRequest req = null;
    try {
        String[][] jsList = {{"returnResponseCodewithQuery.js", "105" },
                {"returnResponseCodewithQuery.js", "301" },
                {"returnResponseCodewithQuery.js", "303" }, {"returnResponseCodewithQuery.js", "307" } };
        for (String[] testSrc : jsList) {
            // ? Dav?put
            if (isServiceTest) {
                putScript(testSrc[0], "test.js");
                url = requestUrl() + "&status=" + testSrc[1];
            } else {
                url = requestUrl(testSrc[0]) + "&status=" + testSrc[1];
            }
            // ?
            req = new PersoniumRequestBuilder().url(url).method("GET").token(token).build();
            req.setHeader(KEY_HEADER_BASEURL, baseUrl);
            String version = getVersion();
            if (version != null && !(version.equals(""))) {
                req.setHeader("X-Personium-Version", version);
            }
            // ???
            HttpResponse objResponse = httpClient.execute(req);
            PersoniumResponse dcRes = new PersoniumResponse(objResponse);
            assertEquals(500, dcRes.getStatusCode());
            String expectedMessage = String.format("Server Error : response status illegal type. status: %s",
                    testSrc[1]);
            assertEquals(expectedMessage, dcRes.bodyAsString());
            EntityUtils.consume(objResponse.getEntity());
        }
    } catch (DaoException e) {
        fail(e.getMessage());
    } catch (ClientProtocolException e) {
        fail(e.getMessage());
    } catch (IOException e) {
        fail(e.getMessage());
    } finally {
        if (isServiceTest) {
            // ?Dav?del
            try {
                testSvcCol.del("test.js");
            } catch (DaoException e) {
                fail(e.getMessage());
            }
        }
    }
}