Java Code Examples for org.apache.http.client.methods.HttpPut#setHeader()

The following examples show how to use org.apache.http.client.methods.HttpPut#setHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleRestClient.java    From canvas-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Response sendApiPut(OauthToken token, String url, Map<String, List<String>> putParameters,
                           int connectTimeout, int readTimeout) throws InvalidOauthTokenException, IOException {
    LOG.debug("Sending API PUT request to URL: " + url);
    Response response = new Response();
    HttpClient httpClient = createHttpClient(connectTimeout, readTimeout);
    Long beginTime = System.currentTimeMillis();
    HttpPut httpPut = new HttpPut(url);
    httpPut.setHeader("Authorization", "Bearer" + " " + token.getAccessToken());
    List<NameValuePair> params = convertParameters(putParameters);

    httpPut.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse httpResponse =  httpClient.execute(httpPut);
    String content = handleResponse(httpResponse, httpPut);

    response.setContent(content);
    response.setResponseCode(httpResponse.getStatusLine().getStatusCode());
    Long endTime = System.currentTimeMillis();
    LOG.debug("PUT call took: " + (endTime - beginTime) + "ms");
    return response;
}
 
Example 2
Source File: HC4DavExchangeSession.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
protected CloseableHttpResponse internalCreateOrUpdate(String encodedHref, byte[] mimeContent) throws IOException {
    HttpPut httpPut = new HttpPut(encodedHref);
    httpPut.setHeader("Translate", "f");
    httpPut.setHeader("Overwrite", "f");
    if (etag != null) {
        httpPut.setHeader("If-Match", etag);
    }
    if (noneMatch != null) {
        httpPut.setHeader("If-None-Match", noneMatch);
    }
    httpPut.setHeader("Content-Type", "message/rfc822");
    httpPut.setEntity(new ByteArrayEntity(mimeContent, ContentType.getByMimeType("message/rfc822")));
    try (CloseableHttpResponse response = httpClientAdapter.execute(httpPut)) {
        return response;
    }
}
 
Example 3
Source File: GeoServerIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static boolean enableWfs() throws ClientProtocolException, IOException {
  final Pair<CloseableHttpClient, HttpClientContext> clientAndContext = createClientAndContext();
  final CloseableHttpClient httpclient = clientAndContext.getLeft();
  final HttpClientContext context = clientAndContext.getRight();
  try {
    final HttpPut command =
        new HttpPut(
            ServicesTestEnvironment.GEOSERVER_REST_PATH
                + "/services/wfs/workspaces/"
                + ServicesTestEnvironment.TEST_WORKSPACE
                + "/settings");
    command.setHeader("Content-type", "text/xml");
    command.setEntity(
        EntityBuilder.create().setFile(
            new File("src/test/resources/wfs-requests/wfs.xml")).setContentType(
                ContentType.TEXT_XML).build());
    final HttpResponse r = httpclient.execute(command, context);
    return r.getStatusLine().getStatusCode() == Status.OK.getStatusCode();
  } finally {
    httpclient.close();
  }
}
 
Example 4
Source File: ODataSuperTenantUserTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private static int sendPUT(String endpoint, String content, String acceptType) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(endpoint);
    httpPut.setHeader("Accept", acceptType);
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        httpPut.setHeader("Content-Type", "application/json");
        httpPut.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPut);
    return httpResponse.getStatusLine().getStatusCode();
}
 
Example 5
Source File: SwiftManager.java    From sync-service with Apache License 2.0 5 votes vote down vote up
@Override
public void createNewWorkspace(Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    HttpClient httpClient = new DefaultHttpClient();

    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 6
Source File: YouTrackClient.java    From vk-java-sdk with MIT License 5 votes vote down vote up
public YouTrackResponse put(String path, Map<String, String> params) throws IOException {
    String url = host + path;
    if (MapUtils.isNotEmpty(params)) {
        url += "?" + mapToGetString(params);
    }

    HttpPut request = new HttpPut(url);
    request.setHeader("Content-Type", CONTENT_TYPE);
    return call(request);
}
 
Example 7
Source File: HttpAPIPinsTest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testPutWithNoWidgetNoPinData() throws Exception {
    HttpPut request = new HttpPut(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/v10");
    request.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
    request.setEntity(new StringEntity("[]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        assertEquals("No pin for update provided.", TestUtil.consumeText(response));
    }
}
 
Example 8
Source File: RequestContentTypeTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void validTextPlainContentType() throws Exception {
  HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Rooms('1')/Seats/$value"));
  put.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.TEXT_PLAIN);
  final HttpResponse response = getHttpClient().execute(put);
  // We expect an internal server error due to the incomplete processor implementation.
  assertEquals(HttpStatusCodes.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
Example 9
Source File: HttpAPIPinsTest.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testPutWithNoWidgetMultivalue() throws Exception {
    HttpPut request = new HttpPut(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/v10");
    request.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
    request.setEntity(new StringEntity("[\"100\", \"101\", \"102\"]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }
}
 
Example 10
Source File: ODataSuperTenantUserTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
private static int sendPUT(String endpoint, String content, String acceptType) throws IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpPut httpPut = new HttpPut(endpoint);
	httpPut.setHeader("Accept", acceptType);
	if (null != content) {
		HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
		httpPut.setHeader("Content-Type", "application/json");
		httpPut.setEntity(httpEntity);
	}
	HttpResponse httpResponse = httpClient.execute(httpPut);
	return httpResponse.getStatusLine().getStatusCode();
}
 
Example 11
Source File: AbstractDatabricksRestClientImpl.java    From databricks-rest-client with Apache License 2.0 5 votes vote down vote up
protected HttpPut makePutMethod(String path, Map<String, Object> data)
    throws UnsupportedEncodingException, JsonProcessingException {
  HttpPut method = new HttpPut(url + path);
  logger.info(method.toString());

  StringEntity requestEntity = makeStringRequestEntity(data);
  method.setEntity(requestEntity);
  method.setHeader("Accept", "application/json");
  method.setHeader("Content-type", "application/json");
  return method;
}
 
Example 12
Source File: ServiceLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenUpdateUnchangedCourse_thenReceiveNotModifiedResponse() throws IOException {
    final HttpPut httpPut = new HttpPut(BASE_URL + "1");
    final InputStream resourceStream = this.getClass().getClassLoader().getResourceAsStream("unchanged_course.xml");
    httpPut.setEntity(new InputStreamEntity(resourceStream));
    httpPut.setHeader("Content-Type", "text/xml");

    final HttpResponse response = client.execute(httpPut);
    assertEquals(304, response.getStatusLine().getStatusCode());
}
 
Example 13
Source File: Consultant.java    From consultant with Apache License 2.0 5 votes vote down vote up
public void deregisterService() {
	if (!registered.compareAndSet(true, false)) {
		log.warn("Cannot deregister the service, as service wasn't registered or was already deregistered!");
		return;
	}

	String serviceId = id.getInstance().get();
	String url = consulUri + "/v1/agent/service/deregister/" + serviceId;
	log.info("Deregistering service from Consul: {}", id);

	HttpPut request = new HttpPut(url);
	request.setHeader("User-Agent", "Consultant");
	try (CloseableHttpResponse response = http.execute(request)) {
		int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode >= 200 && statusCode < 400) {
			return;
		}
		log.error("Could not deregister service, status: " + statusCode);
		String body = EntityUtils.toString(response.getEntity());
		throw new ConsultantException("Could not deregister service", new ConsulException(statusCode, body));
	}
	catch (IOException | RuntimeException e) {
		registered.set(true);
		log.error("Could not deregister service!", e);
		throw new ConsultantException(e);
	}
}
 
Example 14
Source File: RequestContentTypeTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void validApplicationXmlContentType() throws Exception {
  HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Rooms('1')"));
  put.setHeader(HttpHeaders.CONTENT_TYPE, HttpContentType.APPLICATION_XML);
  final HttpResponse response = getHttpClient().execute(put);
  // We expect an internal server error due to the incomplete processor implementation.
  assertEquals(HttpStatusCodes.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
Example 15
Source File: SwiftManager.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void removeUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains("," + tenantUser)) {
        permissions.replace("," + tenantUser, "");
    } else if (permissions.contains(tenantUser)) {
        permissions.replace(tenantUser, "");
    } else {
        return;
    }

    HttpClient httpClient = new DefaultHttpClient();
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 16
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void removeUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains("," + tenantUser)) {
        permissions.replace("," + tenantUser, "");
    } else if (permissions.contains(tenantUser)) {
        permissions.replace(tenantUser, "");
    } else {
        return;
    }

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 17
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void grantUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains(tenantUser)) {
        return;
    }

    permissions += "," + tenantUser;

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 18
Source File: UploadAble.java    From neembuu-uploader with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void run() {
    try {
        if (uploadAbleAccount.loginsuccessful) {
            httpContext = uploadAbleAccount.getHttpContext();
            maxFileSizeLimit = 2147483648L; // 2 GB
        } else {
            cookieStore = new BasicCookieStore();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
            maxFileSizeLimit = 2147483648L; // 2 GB
        }

        if (file.length() > maxFileSizeLimit) {
            throw new NUMaxFileSizeException(maxFileSizeLimit, file.getName(), host);
        }
        uploadInitialising();
        initialize();

        // http://up.uploadable.ch/u/username/e/sid
        HttpPut httpPut = new HttpPut(uploadURL);
        MonitoredFileEntity fileEntity = createMonitoredFileEntity();
        httpPut.setEntity(fileEntity);
        
        //Set the headers
        httpPut.setHeader("Origin", "https://www.uploadable.ch");
        httpPut.setHeader("X-File-Name", file.getName());
        httpPut.setHeader("X-File-Size", Long.toString(file.length()));
        
        NULogger.getLogger().log(Level.INFO, "executing request {0}", httpPut.getRequestLine());
        NULogger.getLogger().info("Now uploading your file into UploadAble.ch");
        uploading();
        httpResponse = httpclient.execute(httpPut, httpContext);
        responseString = EntityUtils.toString(httpResponse.getEntity());
        
        //Read the links
        gettingLink();
        upload_code = StringUtils.stringBetweenTwoStrings(responseString, "\"shortenCode\":\"", "\"");
        delete_code = StringUtils.stringBetweenTwoStrings(responseString, "\"deleteCode\":\"", "\"");
        host_filename = StringUtils.stringBetweenTwoStrings(responseString, "\"fileName\":\"", "\"");
        
        downloadlink = "https://www.uploadable.ch/file/" + upload_code + "/" + host_filename;
        deletelink = "https://www.uploadable.ch/file/" + upload_code + "/delete/" + delete_code;
        
        NULogger.getLogger().log(Level.INFO, "Delete link : {0}", deletelink);
        NULogger.getLogger().log(Level.INFO, "Download link : {0}", downloadlink);
        downURL = downloadlink;
        delURL = deletelink;
        
        uploadFinished();
    } catch(NUException ex){
        ex.printError();
        uploadInvalid();
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, e);

        uploadFailed();
    }
}
 
Example 19
Source File: ZephyrHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 4 votes vote down vote up
@Override
public void setHeader(HttpPut httput) {
    httput.setHeader("zapiAccessKey", OPTIONS.get("AccessKey"));
    httput.setHeader("Content-Type", "application/json");
}
 
Example 20
Source File: GatewayBasicFuncTest.java    From knox with Apache License 2.0 4 votes vote down vote up
@Test( timeout = TestUtils.MEDIUM_TIMEOUT )
public void testEncodedForwardSlash() throws IOException {
  LOG_ENTER();
  String username = "hbase";
  String password = "hbase-password";

  String resourceName = "hbase/table-data";
  String singleRowPath = "/table/%2F%2Ftestrow";

  //PUT request
  driver.getMock( "WEBHBASE" )
      .expect()
      .method( "PUT" )
      .requestURI( singleRowPath ) // Need to use requestURI since pathInfo is url decoded
      .contentType( ContentType.JSON.toString() )
      .respond()
      .status( HttpStatus.SC_OK );

  CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
  UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
  credentialsProvider.setCredentials(AuthScope.ANY, credentials);
  // Show that normalizing from HttpClient doesn't change the behavior of %2F handling
  // with HttpClient 4.5.8+ - HTTPCLIENT-1968
  RequestConfig requestConfig = RequestConfig.custom().setNormalizeUri(false).build();
  try(CloseableHttpClient httpClient = HttpClients.custom()
      .setDefaultCredentialsProvider(credentialsProvider)
      .setDefaultRequestConfig(requestConfig)
      .build()) {

    HttpPut httpPut = new HttpPut(driver.getUrl("WEBHBASE") + singleRowPath);
    httpPut.setHeader("X-XSRF-Header", "jksdhfkhdsf");
    httpPut.setHeader(HttpHeaders.CONTENT_TYPE, org.apache.http.entity.ContentType.APPLICATION_JSON.getMimeType());
    httpPut.setEntity(new ByteArrayEntity(driver.getResourceBytes(resourceName + ".json")));

    HttpResponse response = httpClient.execute(httpPut);
    assertEquals(200, response.getStatusLine().getStatusCode());
  }
  driver.assertComplete();

  driver.getMock( "WEBHBASE" )
  .expect()
  .method( "PUT" )
  .requestURI( singleRowPath ) // Need to use requestURI since pathInfo is url decoded
  .contentType( ContentType.JSON.toString() )
  .respond()
  .status( HttpStatus.SC_OK );

  // There is no way to change the normalization behavior of the
  // HttpClient created by rest-assured since RequestConfig isn't
  // exposed. Instead the above test uses HttpClient directly,
  // this shows that url normalization doesn't matter with 4.5.8+.
  // If this view changes, don't use rest-assured for this type of
  // testing.
  // See: https://github.com/rest-assured/rest-assured/issues/497
  given()
  .urlEncodingEnabled(false) // make sure to avoid rest-assured automatic url encoding
  .auth().preemptive().basic( username, password )
  .header("X-XSRF-Header", "jksdhfkhdsf")
  .body( driver.getResourceBytes( resourceName + ".json" ) )
  .contentType( ContentType.JSON.toString() )
  .then()
  .statusCode( HttpStatus.SC_OK )
  .when().put(driver.getUrl("WEBHBASE") + singleRowPath);
  driver.assertComplete();

  LOG_EXIT();
}