Example usage for org.apache.http.message BasicHeader BasicHeader

List of usage examples for org.apache.http.message BasicHeader BasicHeader

Introduction

In this page you can find the example usage for org.apache.http.message BasicHeader BasicHeader.

Prototype

public BasicHeader(String str, String str2) 

Source Link

Usage

From source file:com.kolich.havalo.client.api.PutTest.java

@Test
public void putLongName() throws Exception {
    // Trying to stay under the default Tomcat maxHttpHeaderSize of 8KB
    // http://stackoverflow.com/questions/6837505/setting-max-http-header-size-with-ajp-tomcat-6-0
    // http://stackoverflow.com/questions/1730158/how-to-set-the-ajp-packet-size-in-tomcat
    // Apparently the max header size in Jetty is less around 4KB
    final String[] prefixes = getRandomPrefix(200);
    // PUT a sample object
    final Either<HttpFailure, FileObject> put = client_.putObject(getBytesUtf8(SAMPLE_JSON_OBJECT),
            new Header[] { new BasicHeader(CONTENT_TYPE, "application/json") }, prefixes);
    assertTrue("Failed to PUT long sample object.", put.success());
    // Tear down/*from www  . j  av  a 2 s  .  co  m*/
    final Either<HttpFailure, Integer> delete = client_.deleteObject(prefixes);
    assertTrue("Failed to DELETE long sample object.", delete.success());
    assertTrue("Failed to DELETE long sample object -- bad response code", delete.right() == SC_NO_CONTENT);
}

From source file:org.envirocar.app.dao.remote.RemoteSensorDAO.java

private String registerSensor(String sensorString)
        throws IOException, NotConnectedException, UnauthorizedException, ResourceConflictException {

    HttpPost postRequest = new HttpPost(ECApplication.BASE_URL + "/sensors");

    StringEntity se = new StringEntity(sensorString);
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

    postRequest.setEntity(se);/*from   www  .java 2s .co m*/

    HttpResponse response = super.executePayloadRequest(postRequest);

    Header[] h = response.getAllHeaders();

    String location = "";
    for (int i = 0; i < h.length; i++) {
        if (h[i].getName().equals("Location")) {
            location += h[i].getValue();
            break;
        }
    }
    logger.info("location: " + location);

    return location.substring(location.lastIndexOf("/") + 1, location.length());
}

From source file:com.geertvanderploeg.kiekeboek.client.NetworkUtilities.java

/**
 * Connects to the server, authenticates the provided username and
 * password./*from   www . j  ava  2s . co m*/
 * 
 * @param username The user's username
 * @param password The user's password
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return boolean The boolean result indicating whether the user was
 *         successfully authenticated.
 */
public static boolean authenticate(String username, String password, Handler handler, final Context context) {
    final HttpResponse resp;

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("_method", "POST"));
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new AssertionError(e);
    }
    final HttpPost post = new HttpPost(context.getString(AUTH_URI_RESOURCE));
    post.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
    post.setEntity(entity);
    HttpClient localHttpClient = getHttpClient();
    Log.d(TAG, "POST-ing params to URL '" + context.getString(AUTH_URI_RESOURCE) + "': " + params);
    try {
        resp = localHttpClient.execute(post);
        Log.d(TAG, "Authentication response status line: " + resp.getStatusLine());
        Log.d(TAG, "Authentication response headers: " + Arrays.asList(resp.getAllHeaders()));
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                && resp.getHeaders("Location") != null
                && resp.getHeaders("Location")[0].getValue().contains("/intranet/people")) {
            Log.v(TAG, "Successful authentication");
            sendResult(true, handler, context);
            resp.getEntity().consumeContent();
            return true;
        } else {
            Log.v(TAG, "Error authenticating " + resp.getStatusLine());
            sendResult(false, handler, context);
            resp.getEntity().consumeContent();
            return false;
        }
    } catch (final IOException e) {
        Log.v(TAG, "IOException when getting authtoken", e);
        sendResult(false, handler, context);
        return false;
    } finally {
        Log.v(TAG, "getAuthtoken completing");
    }
}

From source file:ch.cyberduck.core.oauth.OAuth2RequestInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (tokens.isExpired()) {
        try {/*from  ww  w . j av a  2s. c o  m*/
            tokens = this.refresh(tokens);
        } catch (BackgroundException e) {
            log.warn(String.format("Failure refreshing OAuth 2 tokens. %s", e.getDetail()));
            throw new IOException(e);
        }
    }
    if (StringUtils.isNotBlank(tokens.getAccessToken())) {
        if (log.isInfoEnabled()) {
            log.info(String.format("Authorizing service request with OAuth2 access token %s",
                    tokens.getAccessToken()));
        }
        request.removeHeaders(HttpHeaders.AUTHORIZATION);
        request.addHeader(new BasicHeader(HttpHeaders.AUTHORIZATION,
                String.format("Bearer %s", tokens.getAccessToken())));
    }
}

From source file:org.fiware.apps.repository.it.collectionService.CollectionServicePostITTest.java

@Test
public void postResource2JsonTest() throws IOException {
    String fileName = "";
    String mimeType = "";
    String contentUrl = "http://localhost:8080/contentUrl/resourceTestPost2";
    String creator = "Me";
    String name = "resourceTestPost2";
    Resource resource = IntegrationTestHelper.generateResource(null, fileName, mimeType, contentUrl, null,
            creator, null, null, name);//w w  w  .  j a v a  2s  . co m

    //Create a resource
    List<Header> headers = new LinkedList<>();
    headers.add(new BasicHeader("Content-Type", "application/json"));
    HttpResponse response = client.postResourceMeta(collection + "/" + collection,
            client.resourceToJson(resource), headers);
    assertEquals(201, response.getStatusLine().getStatusCode());
}

From source file:com.paramedic.mobshaman.activities.AccessTimeActivity.java

public void postAccessTime() {

    Gson g = new Gson();
    String jsonAccessTime = g.toJson(getMobileAccessTime());
    StringEntity entity = null;/*w  w  w .j a v a2 s.c  om*/
    try {
        entity = new StringEntity(jsonAccessTime);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

    //        URL_HC = "http://10.0.3.2/wapimobile/api/mobileaccesstime?licencia=5688923116";

    ServiciosRestClient.post(context, URL_HC, entity, "application/json", new JsonHttpResponseHandler() {
        @Override
        public void onStart() {
            String message = TipoMovimiento == 0 ? "Registrando ingreso..." : "Registrando egreso...";
            pDialog.setMessage(message);
            pDialog.show();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Utils.showToast(getApplicationContext(), "Error " + statusCode + ": " + throwable.getMessage());
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
            super.onFailure(statusCode, headers, throwable, errorResponse);
            Utils.showToast(getApplicationContext(), "Error " + statusCode + ": " + throwable.getMessage());
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject result) {
            Utils.showToast(getApplicationContext(), result.toString());
            startActivity(intent);
        }

        @Override
        public void onFinish() {
            pDialog.dismiss();
        }
    });
}

From source file:io.openkit.OKHTTPClient.java

private static StringEntity getJSONString(JSONObject jsonObject) {
    StringEntity sEntity = null;//w w w  .  j  a  v  a 2 s  . c o m
    try {
        sEntity = new StringEntity(jsonObject.toString(), HTTP.UTF_8);
        sEntity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        return sEntity;
    } catch (UnsupportedEncodingException e) {
        return null;
    }
}

From source file:com.uwindsor.elgg.project.http.SimpleMultipartEntity.java

@Override
public Header getContentType() {

    return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}

From source file:io.liveoak.container.BasicServerTest.java

@Test
public void testServer() throws Exception {

    CompletableFuture<StompMessage> peopleCreationNotification = new CompletableFuture<>();
    CompletableFuture<StompMessage> bobCreationNotification = new CompletableFuture<>();

    StompClient stompClient = new StompClient();

    CountDownLatch subscriptionLatch = new CountDownLatch(1);

    stompClient.connect("localhost", 8080, (client) -> {
        stompClient.subscribe("/testApp/memory/people/*", (subscription) -> {
            subscription.onMessage((msg) -> {
                System.err.println("******* MESSAGE: " + msg);
                if (msg.headers().get("location").equals("/testApp/memory/people")) {
                    peopleCreationNotification.complete(msg);
                } else {
                    bobCreationNotification.complete(msg);
                }/* w  ww  .  java2s .c  o  m*/
            });
            subscription.onReceipt(() -> {
                subscriptionLatch.countDown();
            });
        });
    });

    subscriptionLatch.await();

    Header header = new BasicHeader("Accept", "application/json");

    HttpGet getRequest = null;
    HttpPost postRequest = null;
    HttpPut putRequest = null;
    CloseableHttpResponse response = null;

    System.err.println("TEST #1");
    // Root object should exist.
    getRequest = new HttpGet("http://localhost:8080/testApp/memory");
    getRequest.addHeader(header);

    response = this.httpClient.execute(getRequest);

    //  {
    //    "id" : "memory",
    //    "self" : {
    //      "href" : "/memory"
    //    },
    //   "content" : [ ]
    // }

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    ResourceState state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state.members().size()).isEqualTo(0);

    response.close();

    System.err.println("TEST #2");
    // people collection should not exist.

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people");

    response = this.httpClient.execute(getRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(404);

    response.close();

    System.err.println("TEST #3");
    // create people collection with direct PUT

    putRequest = new HttpPut("http://localhost:8080/testApp/memory/people");
    putRequest.setEntity(new StringEntity("{ \"type\": \"collection\" }"));
    putRequest.setHeader("Content-Type", "application/json");
    response = this.httpClient.execute(putRequest);
    System.err.println("response: " + response);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    response.close();

    System.err.println("TEST #4");
    // people collection should exist now.

    getRequest = new HttpGet("http://localhost:8080/testApp/memory/people");

    response = this.httpClient.execute(getRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    response.close();

    assertThat(peopleCreationNotification.getNow(null)).isNull();

    System.err.println("TEST #5");
    // people collection should be enumerable from the root

    getRequest = new HttpGet("http://localhost:8080/testApp/memory?expand=members");
    getRequest.addHeader(header);

    response = this.httpClient.execute(getRequest);

    //        {
    //          "id" : "memory",
    //          "self" : {
    //            "href" : "/memory"
    //          },
    //          "content" : [ {
    //            "id" : "people",
    //            "self" : {
    //                "href" : "/memory/people"
    //            },
    //            "content" : [ ]
    //          } ]
    //        }

    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state.members().size()).isEqualTo(1);

    ResourceState memoryCollection = state.members().get(0);
    assertThat(memoryCollection.id()).isEqualTo("people");

    assertThat(memoryCollection.uri().toString()).isEqualTo("/testApp/memory/people");

    System.err.println("TEST #6");
    // Post a person

    postRequest = new HttpPost("http://localhost:8080/testApp/memory/people");
    postRequest.setEntity(new StringEntity("{ \"name\": \"bob\" }"));
    postRequest.setHeader("Content-Type", "application/json");

    response = httpClient.execute(postRequest);
    assertThat(response).isNotNull();
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(201);

    state = decode(response);
    assertThat(state).isNotNull();
    assertThat(state).isInstanceOf(ResourceState.class);

    assertThat(state.id()).isNotNull();
    assertThat(state.getProperty("name")).isEqualTo("bob");

    // check STOMP
    System.err.println("TEST #STOMP");
    StompMessage obj = bobCreationNotification.get(30000, TimeUnit.SECONDS);
    assertThat(obj).isNotNull();

    ResourceState bobObjState = decode(obj.content());
    assertThat(bobObjState.getProperty("name")).isEqualTo("bob");

    assertThat(state.getProperty(LiveOak.ID)).isEqualTo(bobObjState.getProperty(LiveOak.ID));
    response.close();
}