Example usage for org.apache.http.client.methods HttpPut setEntity

List of usage examples for org.apache.http.client.methods HttpPut setEntity

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:IoTatWork.NotifyResolutionManager.java

/**
 * //from w  ww .j  ava 2 s  . c o  m
 * @param notification
 * @return
 */
private boolean sendNotification(PendingResolutionNotification notification) {
    String xmlString = notification.toXML();

    String revocationPut = notification.getNotificationUrl() + notification.getRevocationHash();
    System.out.println("\nProcessing notification: " + revocationPut + "\n" + notification.toXML());
    // TODO logEvent
    //IoTatWorkApplication.logger.info("Sending pending resolution notification: "+revocationPut);
    IoTatWorkApplication.logger.info(LogMessage.SEND_RESOLUTION_NOTIFICATION + revocationPut);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPut putRequest = new HttpPut(revocationPut);

    try {
        StringEntity input = new StringEntity(xmlString);

        input.setContentType("application/xml");
        putRequest.setEntity(input);

        HttpResponse response = httpClient.execute(putRequest);

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

        switch (statusCode) {
        case 200:
            IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_200);
            break;
        case 400:
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            String output = br.toString();
            /*
            while ((output = br.readLine()) != null) {
               System.out.println(output);
            }
            */
            JsonParser parser = new JsonParser();
            JsonObject jsonObj = (JsonObject) parser.parse(output);
            String code = jsonObj.get(JSON_PROCESSING_STATUS_CODE).getAsString();

            if (code.equals("NPR400")) {
                IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_400);
            } else if (code.equals("NPR450")) {
                IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_450);
            } else if (code.equals("NPR451")) {
                IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_451);
            }

            break;
        case 404:
            IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_404);
            break;
        case 500:
            IoTatWorkApplication.logger.info(LogMessage.RESOLUTION_NOTIFICATION_RESPONSE_STATUSCODE_500);
            break;
        default:
            break;
        }

        httpClient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return true;

}

From source file:org.sharetask.controller.UserControllerIT.java

@Test
public void testUpdateUser() throws IOException {
    //given//w  w w .  j a  va2 s  .com
    final HttpPut httpPut = new HttpPut(URL_USER);
    httpPut.addHeader(new BasicHeader("Content-Type", "application/json"));
    final StringEntity httpEntity = new StringEntity("{\"username\":\"dev3@shareta.sk\","
            + "\"name\":\"Integration\"," + "\"surName\":\"Test\"," + "\"language\":\"en\"}");
    httpPut.setEntity(httpEntity);

    //when
    final HttpResponse response = getClient().execute(httpPut);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    final String responseData = EntityUtils.toString(response.getEntity());
    Assert.assertTrue(responseData.contains("\"name\":\"Integration\""));
}

From source file:com.crazytest.config.TestCase.java

protected void putWithCredential(String endpoint, List<NameValuePair> params)
        throws MalformedURLException, URISyntaxException, UnsupportedEncodingException {
    String endpointString = hostUrl + endpoint + "?auth-key=" + this.authToken + "&token=" + this.authToken
            + "&userID=" + this.userID;

    URL url = new URL(endpointString);
    URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
            url.getQuery(), url.getRef());

    HttpPut putRequest = new HttpPut(uri);
    putRequest.setEntity(new UrlEncodedFormEntity(params));

    putRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    putRequest.setHeader("User-Agent", "Safari");
    this.putRequest = putRequest;

    LOGGER.info("request: {}", putRequest.getRequestLine());
}

From source file:com.lingeringsocket.mobflare.RpcCoordinator.java

String createFlare(String name, Bundle props) throws Exception {
    HttpPut httpPut = new HttpPut(generateFlareUri(name));
    try {//w  w  w . ja v  a  2  s . c  o m
        JSONObject jsonObj = new JSONObject();
        for (String key : props.keySet()) {
            jsonObj.put(key, props.get(key));
        }
        httpPut.setEntity(new StringEntity(jsonObj.toString()));
        HttpResponse httpResponse = execute(httpPut);
        if (httpResponse.getStatusLine().getStatusCode() == 409) {
            errId = R.string.duplicate_flare_name;
            throw new RuntimeException("Flare name already in use");
        }
        String json = readInputStream(httpResponse.getEntity().getContent());
        JSONTokener tokener = new JSONTokener(json);
        jsonObj = new JSONObject(tokener);
        return jsonObj.getString("name");
    } catch (Exception ex) {
        Log.e(LOGTAG, "HTTP PUT failed", ex);
        throw ex;
    }
}

From source file:org.changhong.sync.web.OAuthConnection.java

@Override
public String put(String uri, String data) throws UnknownHostException {

    // Prepare a request object
    HttpPut httpPut = new HttpPut(uri);

    try {//from  w  ww .  j a v a2  s  .  c o  m
        // The default http content charset is ISO-8859-1, JSON requires UTF-8
        httpPut.setEntity(new StringEntity(data, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return null;
    }

    httpPut.setHeader("Content-Type", "application/json");
    httpPut.addHeader("X-Tomboy-Client", Tomdroid.HTTP_HEADER);
    sign(httpPut);

    // Do not handle redirects, we need to sign the request again as the old signature will be invalid
    HttpResponse response = execute(httpPut);
    return parseResponse(response);
}

From source file:org.privatenotes.sync.web.OAuthConnection.java

@Override
public String put(String uri, String data) throws UnknownHostException {

    // Prepare a request object
    HttpPut httpPut = new HttpPut(uri);

    try {/*from   w  ww  . j ava2  s .c o  m*/
        // The default http content charset is ISO-8859-1, JSON requires UTF-8
        httpPut.setEntity(new StringEntity(data, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        return null;
    }

    httpPut.setHeader("Content-Type", "application/json");
    sign(httpPut);

    // Do not handle redirects, we need to sign the request again as the old signature will be invalid
    HttpResponse response = execute(httpPut);
    return parseResponse(response);
}

From source file:io.apiman.manager.api.gateway.rest.GatewayClient.java

/**
 * @see io.apiman.gateway.api.rest.contract.IServiceResource#publish(io.apiman.gateway.engine.beans.Service)
 *///w ww  . ja  va2s. c o  m
public void publish(Service service) throws PublishingException, NotAuthorizedException {
    try {
        URI uri = new URI(this.endpoint + SERVICES);
        HttpPut put = new HttpPut(uri);
        put.setHeader("Content-Type", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
        String jsonPayload = mapper.writer().writeValueAsString(service);
        HttpEntity entity = new StringEntity(jsonPayload);
        put.setEntity(entity);
        HttpResponse response = httpClient.execute(put);
        int actualStatusCode = response.getStatusLine().getStatusCode();
        if (actualStatusCode >= 300) {
            throw new Exception("Application registration failed: " + actualStatusCode); //$NON-NLS-1$
        }
    } catch (Exception e) {
        // TODO log this error
        throw new RuntimeException(e);
    }
}

From source file:com.getblimp.api.client.Blimp.java

public String put(String resourceUri, BlimpObject data) {
    logger.fine("Entering Blimp.update method.");

    // Response output variable
    String output = null;/*from  w ww. j av  a 2  s. c o m*/

    try {

        HttpPut tmpPut = (HttpPut) createRequestMethod(createRequestUrl(resourceUri), HttpMethods.PUT);

        tmpPut.setEntity(createStringEntity(data));

        output = execute(tmpPut);

    } catch (UnsupportedEncodingException e) {
        errorHandler(e);
    } catch (ClientProtocolException e) {
        errorHandler(e);
    } catch (IOException e) {
        errorHandler(e);
    } catch (Exception e) {
        errorHandler(e);
    }

    logger.fine("Blimp.update output: " + output);
    return output;
}