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

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

Introduction

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

Prototype

public HttpPut(final String uri) 

Source Link

Usage

From source file:com.helger.httpclient.HttpClientHelper.java

@Nonnull
public static HttpRequestBase createRequest(@Nonnull final EHttpMethod eHTTPMethod,
        @Nonnull final ISimpleURL aSimpleURL) {
    final String sURL = aSimpleURL.getAsStringWithEncodedParameters();
    switch (eHTTPMethod) {
    case DELETE:/*from ww w. j  a v  a 2  s .  c o  m*/
        return new HttpDelete(sURL);
    case GET:
        return new HttpGet(sURL);
    case HEAD:
        return new HttpHead(sURL);
    case OPTIONS:
        return new HttpOptions(sURL);
    case TRACE:
        return new HttpTrace(sURL);
    case POST:
        return new HttpPost(sURL);
    case PUT:
        return new HttpPut(sURL);
    default:
        throw new IllegalStateException("Unsupported HTTP method: " + eHTTPMethod);
    }
}

From source file:com.arthackday.killerapp.GCMIntentService.java

@Override
protected void onRegistered(Context ctxt, String regId) {
    Log.i(getClass().getSimpleName(), "onRegistered: " + regId);

    URL url;/*from w  w  w .ja va  2s  .c  o m*/
    try {
        url = new URL(String.format(GCM_URL, this.getPackageName(), regId));

        // --This code works for updating a record from the feed--
        HttpPut httpPut = new HttpPut(url.toString());

        // Send request to WCF service
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpResponse response = httpClient.execute(httpPut);
        HttpEntity entity1 = response.getEntity();

        if (entity1 != null && (response.getStatusLine().getStatusCode() == 201
                || response.getStatusLine().getStatusCode() == 200)) {
            // --just so that you can view the response, this is optional--
            int sc = response.getStatusLine().getStatusCode();
            String sl = response.getStatusLine().getReasonPhrase();
        } else {
            int sc = response.getStatusLine().getStatusCode();
            String sl = response.getStatusLine().getReasonPhrase();
        }

    } catch (MalformedURLException e) {
        Log.wtf("ArtHackDay", "failure");
    } catch (ClientProtocolException e) {
        Log.wtf("ArtHackDay", "failure");
    } catch (IOException e) {
        Log.wtf("ArtHackDay", "failure");
    }
}

From source file:tv.arte.resteventapi.core.clients.RestEventApiRestClient.java

/**
 * Executes the REST request described by the {@link RestEvent}
 * /*from w w  w.j a v  a  2 s . c o  m*/
 * @param restEvent The {@link RestEvent} to process
 * @return A result of the execution
 * @throws RestEventApiRuntimeException In case of non managed errors
 */
public static RestClientExecutionResult execute(final RestEvent restEvent) throws RestEventApiRuntimeException {
    RestClientExecutionResult result = new RestClientExecutionResult();
    String url = restEvent.getUrl();
    CloseableHttpClient client = null;
    HttpUriRequest request = null;
    Integer responseCode = null;

    try {
        //Request custom configs
        RequestConfig.Builder requestBuilder = RequestConfig.custom();
        requestBuilder = requestBuilder.setConnectTimeout(restEvent.getTimeout());
        requestBuilder = requestBuilder.setConnectionRequestTimeout(restEvent.getTimeout());

        client = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build();

        //Determine the method to execute
        switch (restEvent.getMethod()) {
        case GET:
            request = new HttpGet(url);
            break;
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        case DELETE:
            request = new HttpDelete(url);
            break;
        case PATCH:
            request = new HttpPatch(url);
            break;
        case HEAD:
            request = new HttpHead(url);
            break;
        default:
            throw new RestEventApiRuntimeException("RestEventAPI unsupported HTTP method");
        }

        //Set the body for eligible methods
        if (restEvent.getBody() != null && request instanceof HttpEntityEnclosingRequestBase) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(new StringEntity(restEvent.getBody()));
        }

        //Set headers
        if (CollectionUtils.isNotEmpty(restEvent.getHeaders())) {
            for (String strHeader : restEvent.getHeaders()) {
                CharArrayBuffer headerBuffer = new CharArrayBuffer(strHeader.length() + 1);
                headerBuffer.append(strHeader);
                request.addHeader(new BufferedHeader(headerBuffer));
            }
        }

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

        result.setState(RestClientCallState.OK);
    } catch (ConnectTimeoutException e) {
        result.setState(RestClientCallState.TIMEOUT);
    } catch (Exception e) {
        throw new RestEventApiRuntimeException("Un error occured while processing rest event", e);
    } finally {
        result.setResponseCode(responseCode);

        try {
            client.close();
        } catch (Exception e2) {
            logger.warn("Unable to close HTTP client", e2);
        }
    }

    return result;
}

From source file:org.bishoph.oxdemo.util.DeleteTask.java

@Override
protected JSONObject doInBackground(Object... params) {
    try {/*from   ww w  .  ja v a2s.co  m*/
        String uri = (String) params[0];
        int object_id = (Integer) params[1];
        Log.v("OXDemo", "Attempting to delete task " + object_id + " in folder " + folder_id + " on " + uri);

        // [{"id":25,"folder":27}]
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("id", object_id);
        jsonobject.put("folder", folder_id);
        JSONArray jsonarray = new JSONArray();
        jsonarray.put(jsonobject);

        HttpPut httput = new HttpPut(uri);
        StringEntity stringentity = new StringEntity(jsonarray.toString());
        Log.v("OXDemo", "JSON ? " + stringentity);
        stringentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8")); // 
        httput.setHeader("Accept", "application/json, text/javascript");
        httput.setHeader("Content-type", "application/json");
        httput.setEntity(stringentity);

        HttpResponse response = httpclient.execute(httput, localcontext);
        Log.v("OXDemo", "Delete task " + object_id);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n");
        JSONObject jsonObj = new JSONObject(result);
        return jsonObj;
    } catch (JSONException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (ClientProtocolException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (IOException e) {
        Log.e("OXDemo", e.getMessage());
    }
    return null;
}

From source file:org.elasticsearch.shell.command.HttpPutCommand.java

@SuppressWarnings("unused")
public HttpCommandResponse execute(String url, String body, String mimeType) throws IOException {
    HttpPut httpPut = new HttpPut(url);
    httpPut.setEntity(new StringEntity(body, ContentType.create(mimeType)));
    return new HttpCommandResponse(shellHttpClient.getHttpClient().execute(httpPut));
}

From source file:com.meltmedia.cadmium.cli.ApiCommand.java

/**
 * Sends acl request to cadmium.//from  w  ww.j a  va  2  s  . co m
 * 
 * @param site
 * @param op
 * @param path
 * @return
 * @throws Exception
 */
public static String[] sendRequest(String token, String site, OPERATION op, String path) throws Exception {
    HttpClient client = httpClient();
    HttpUriRequest message = null;
    if (op == OPERATION.DISABLE) {
        message = new HttpPut(site + ENDPOINT + path);
    } else if (op == OPERATION.ENABLE) {
        message = new HttpDelete(site + ENDPOINT + path);
    } else {
        message = new HttpGet(site + ENDPOINT);
    }
    addAuthHeader(token, message);

    HttpResponse resp = client.execute(message);
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String results = EntityUtils.toString(resp.getEntity());
        return new Gson().fromJson(results, String[].class);
    }
    return null;
}

From source file:edu.jhu.pha.vospace.protocol.HttpPutProtocolHandler.java

@Override
public void invoke(JobDescription job) throws IOException {
    String putFileUrl = job.getProtocols()
            .get(SettingsServlet.getConfig().getString("transfers.protocol.httpput"));

    StorageManager backend = StorageManagerFactory.getStorageManager(job.getUsername());

    HttpClient client = MyHttpConnectionPoolProvider.getHttpClient();
    InputStream fileInp = backend.getBytes(job.getTargetId().getNodePath());

    HttpPut put = new HttpPut(putFileUrl);

    Node node = NodeFactory.getNode(job.getTargetId(), job.getUsername());

    put.setEntity(new InputStreamEntity(fileInp, node.getNodeInfo().getSize()));

    try {//from   w w w .  j  a  v a 2 s . c  om
        HttpResponse response = client.execute(put);
        response.getEntity().getContent().close();
    } catch (IOException ex) {
        put.abort();
        ex.printStackTrace();
        throw ex;
    } finally {
        try {
            if (null != fileInp)
                fileInp.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.manifoldcf.agents.output.opensearchserver.OpenSearchServerScheduler.java

public OpenSearchServerScheduler(HttpClient client, OpenSearchServerConfig config, String schedulerName)
        throws ManifoldCFException {
    super(client, config);
    String path = StringUtils.replace(PATH, "{index_name}", URLEncoder.encode(config.getIndexName()));
    path = StringUtils.replace(path, "{scheduler_name}", URLEncoder.encode(schedulerName));
    StringBuffer url = getApiUrlV2(path);
    HttpPut put = new HttpPut(url.toString());
    put.setEntity(new StringEntity("{}", ContentType.APPLICATION_JSON));
    call(put);//  w  w w.  j  a  v a 2s  .com
}

From source file:com.urbancode.ud.client.SystemClient.java

public void addUserToTeam(String user, String team, String type) throws IOException {
    String uri = url + "/cli/teamsecurity/users?user=" + encodePath(user) + "&team=" + encodePath(team)
            + "&type=" + encodePath(type);
    HttpPut method = new HttpPut(uri);
    invokeMethod(method);//from   w ww  . j a v  a2s.  co m
}

From source file:fr.efl.chaine.xslt.GauloisListenerTest.java

@Test
public void listenerStart() throws Exception {
    GauloisPipe piper = new GauloisPipe(configFactory);
    ConfigUtil cu = new ConfigUtil(configFactory.getConfiguration(), piper.getUriResolver(),
            "./src/test/resources/listener/start.xml");
    Config config = cu.buildConfig(emptyInputParams);
    config.setLogFileSize(true);/*from  w ww .j av a  2 s  . co m*/
    config.verify();
    assertEquals("Port escape does not work", 8123, config.getSources().getListener().getPort());
    assertEquals("STOP keyword escape does not work", "ARRETE",
            config.getSources().getListener().getStopKeyword());
    piper.setConfig(config);
    piper.setInstanceName("LISTENER_1");
    piper.launch();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    File userDir = new File(System.getProperty("user.dir"));
    File source = new File(userDir, "src/test/resources/source.xml");
    HttpPut put = new HttpPut("http://localhost:8123/?url="
            + URLEncoder.encode(source.toURI().toURL().toExternalForm(), "UTF-8"));
    HttpResponse response = httpClient.execute(put);
    System.out.println(response.getStatusLine().toString());
    assertEquals(200, response.getStatusLine().getStatusCode());
    put.releaseConnection();
    // the same, with accents
    source = new File(userDir, "src/test/resources/source_avec_accents.xml");
    put = new HttpPut("http://localhost:8123/?url="
            + URLEncoder.encode(source.toURI().toURL().toExternalForm(), "UTF-8"));
    response = httpClient.execute(put);
    System.out.println(response.getStatusLine().toString());
    assertEquals(200, response.getStatusLine().getStatusCode());
    put.releaseConnection();

    // we must let GauloisPipe process submitted file, because JUnit closes since the tested method returns.
    Thread.sleep(1000);
    File outputDir = new File("target/generated-test-files");
    File target = new File(outputDir, "source-listen1.xml");
    assertTrue("File " + target.toString() + " does not exists", target.exists());
    HttpDelete delete = new HttpDelete("http://localhost:8123/?keyword=ARRETE");
    response = httpClient.execute(delete);
    System.out.println(response.getStatusLine().toString());
    assertEquals(200, response.getStatusLine().getStatusCode());
    delete.releaseConnection();
    File appendee = new File(outputDir, "listener-appendee.txt");
    assertTrue(appendee.getAbsolutePath() + " does not exists.", appendee.exists());
    String previousLine = null;
    try (BufferedReader br = new BufferedReader(new FileReader(appendee))) {
        String currentLine = br.readLine();
        while (currentLine != null) {
            previousLine = currentLine;
            currentLine = br.readLine();
        }
    }
    assertEquals(appendee.getAbsolutePath() + " does not ends with \"EOF\"", "EOF", previousLine);
}