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

The following examples show how to use org.apache.http.client.methods.HttpPut#addHeader() . 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: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void setAuthentication(String level, String restServerName)
		throws ClientProtocolException, IOException {
	DefaultHttpClient client = new DefaultHttpClient();

	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String body = "{\"authentication\": \"" + level + "\"}";

	HttpPut put = new HttpPut("http://" + host_name + ":" + admin_port + "/manage/v2/servers/" + restServerName
			+ "/properties?server-type=http&group-id=Default");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));

	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if (respEntity != null) {
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	client.getConnectionManager().shutdown();
}
 
Example 2
Source File: HttpUtils.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * Put String
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method,
		Map<String, String> headers,
		Map<String, String> querys,
		String body)
           throws Exception {
   	HttpClient httpClient = wrapClient(host);

   	HttpPut request = new HttpPut(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (StringUtils.isNotBlank(body)) {
       	request.setEntity(new StringEntity(body, "utf-8"));
       }

       return httpClient.execute(request);
   }
 
Example 3
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * Put String
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		String body)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPut request = new HttpPut(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (StringUtils.isNotBlank(body)) {
       	request.setEntity(new StringEntity(body, "utf-8"));
       }

       return httpClient.execute(request);
   }
 
Example 4
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 6 votes vote down vote up
/**
 * HTTP PUT 字符串
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param body
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPut put = new HttpPut(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (StringUtils.isNotBlank(body)) {
        put.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return convert(httpClient.execute(put));
}
 
Example 5
Source File: ClientApiFunctionalTest.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void modifyConcurrentUsersOnHttpServer(String restServerName, int numberOfUsers) throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String extSecurityrName = "";
	String body = "{\"group-name\": \"Default\", \"concurrent-request-limit\":\"" + numberOfUsers + "\"}";

	HttpPut put = new HttpPut("http://" + host + ":" + admin_Port + "/manage/v2/servers/" + restServerName
			+ "/properties?server-type=http");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));
	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if (respEntity != null) {
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	client.getConnectionManager().shutdown();
}
 
Example 6
Source File: SwiftOutputStream.java    From stocator with Apache License 2.0 6 votes vote down vote up
/**
 * Default constructor
 *
 * @param account           JOSS account object
 * @param url               URL connection
 * @param targetContentType Content type
 * @param metadata          input metadata
 * @param connectionManager SwiftConnectionManager
 */
public SwiftOutputStream(
    JossAccount account,
    URL url,
    final String targetContentType,
    Map<String, String> metadata,
    SwiftConnectionManager connectionManager
) {
  mUrl = url;
  mAccount = account;
  client = connectionManager.createHttpConnection();
  contentType = targetContentType;

  pipOutStream = new PipedOutputStream();
  bufOutStream = new BufferedOutputStream(pipOutStream, Constants.SWIFT_DATA_BUFFER);

  // Append the headers to the request
  request = new HttpPut(mUrl.toString());
  request.addHeader("X-Auth-Token", account.getAuthToken());
  if (metadata != null && !metadata.isEmpty()) {
    for (Map.Entry<String, String> entry : metadata.entrySet()) {
      request.addHeader("X-Object-Meta-" + entry.getKey(), entry.getValue());
    }
  }
}
 
Example 7
Source File: AliHttpUtils.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * Put String
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method,
                                 Map<String, String> headers,
                                 Map<String, String> querys,
                                 String body)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
}
 
Example 8
Source File: StreamingAnalyticsServiceV1.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Submit the job from the built artifact.
 */
@Override
protected JsonObject submitBuildArtifact(CloseableHttpClient httpclient,
        JsonObject jobConfigOverlays, String submitUrl)
        throws IOException {
    HttpPut httpput = new HttpPut(submitUrl);
    httpput.addHeader("Authorization", getAuthorization());
    httpput.addHeader("content-type", ContentType.APPLICATION_JSON.getMimeType());

    StringEntity params = new StringEntity(jobConfigOverlays.toString(),
            ContentType.APPLICATION_JSON);
    httpput.setEntity(params);

    JsonObject jso = StreamsRestUtils.getGsonResponse(httpclient, httpput);

    TRACE.info("Streaming Analytics service (" + getName() + "): submit job response: " + jso.toString());
    return jso;
}
 
Example 9
Source File: AmforeasRestClient.java    From amforeas with GNU General Public License v3.0 6 votes vote down vote up
public Optional<AmforeasResponse> update (String resource, String pk, String id, String json) {
    final URI url = this.build(String.format(item_path, root, alias, resource, id)).orElseThrow();
    final HttpPut req = new HttpPut(url);
    req.addHeader(this.accept);
    req.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    req.addHeader("Primary-Key", pk);

    try {
        req.setEntity(new StringEntity(json));
    } catch (UnsupportedEncodingException e) {
        final String msg = "Failed to encode JSON body " + e.getMessage();
        l.error(msg);
        return Optional.of(new ErrorResponse(resource, Response.Status.BAD_REQUEST, msg));
    }

    return this.execute(req);
}
 
Example 10
Source File: HDInsightInstance.java    From reef with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a HttpPut request with all the common headers.
 * @param url
 * @return
 */
private HttpPut preparePut(final String url) {
  final HttpPut httpPut = new HttpPut(this.instanceUrl + url);
  for (final Header header : this.headers) {
    httpPut.addHeader(header);
  }
  return httpPut;
}
 
Example 11
Source File: Utils.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public static String httpPUT(String url, String type, String data) throws Exception {
	HttpPut request = new HttpPut(url);
       StringEntity params = new StringEntity(data, "utf-8");
       request.addHeader("content-type", type);
       request.setEntity(params);
	DefaultHttpClient client = new DefaultHttpClient();
       HttpResponse response = client.execute(request);
	return fetchResponse(response);
}
 
Example 12
Source File: TransportRequestBuilder.java    From devops-cm-client with Apache License 2.0 5 votes vote down vote up
public HttpPut updateTransport(String id)
{
  
  HttpPut put = new HttpPut(createTransportUri(id,null));
  put.addHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
  return put;

}
 
Example 13
Source File: BPMNTestUtils.java    From product-ei with Apache License 2.0 5 votes vote down vote up
public static HttpResponse doPut(String url, Object payload, String user, String password) throws IOException {
    String restUrl = getRestEndPoint(url);
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(restUrl);
    put.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password), "UTF-8", false));
    put.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(put);
    return response;
}
 
Example 14
Source File: HttpRestUtils.java    From spring-boot-study with MIT License 5 votes vote down vote up
/**
     * put 方法
     * @param url put 的 url
     * @param data 数据 application/json 的时候 为json格式
     * @param heads Http Head 参数
     * */
    public  static String put(String url,String data,Map<String,String> heads) throws IOException{
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPut httpPut = new HttpPut(url);
            if(heads!=null){
                Set<String> keySet=heads.keySet();
                for(String s:keySet){
                    httpPut.addHeader(s,heads.get(s));
                }
            }
            //json 示例
//            httpPut.setHeader("Accept", "application/json");
//            httpPut.setHeader("Content-type", "application/json");
//            String json = "{\r\n" + "  \"firstName\": \"Ram\",\r\n" + "  \"lastName\": \"Jadhav\",\r\n" +
//                    "  \"emailId\": \"[email protected]\",\r\n" +
//                    "  \"createdAt\": \"2018-09-11T11:19:56.000+0000\",\r\n" + "  \"createdBy\": \"Ramesh\",\r\n" +
//                    "  \"updatedAt\": \"2018-09-11T11:26:31.000+0000\",\r\n" + "  \"updatedby\": \"Ramesh\"\r\n" +
//                    "}";
            StringEntity stringEntity = new StringEntity(data);
            httpPut.setEntity(stringEntity);

            System.out.println("Executing request " + httpPut.getRequestLine());

            // Create a custom response handler
            ResponseHandler < String > responseHandler = response -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
            };
            String responseBody = httpclient.execute(httpPut, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);
            return  responseBody;
        }
    }
 
Example 15
Source File: StoregateMultipartWriteFeature.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void close() throws IOException {
    try {
        if(close.get()) {
            log.warn(String.format("Skip double close of stream %s", this));
            return;
        }
        if(null != canceled.get()) {
            return;
        }
        if(overall.getLength() <= 0) {
            final StoregateApiClient client = session.getClient();
            final HttpPut put = new HttpPut(location);
            put.addHeader(HttpHeaders.CONTENT_RANGE, "bytes */0");
            final HttpResponse response = client.getClient().execute(put);
            try {
                switch(response.getStatusLine().getStatusCode()) {
                    case HttpStatus.SC_OK:
                    case HttpStatus.SC_CREATED:
                        final FileMetadata result = new JSON().getContext(FileMetadata.class).readValue(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8),
                            FileMetadata.class);
                        overall.setVersion(new VersionId(result.getId()));
                    case HttpStatus.SC_NO_CONTENT:
                        break;
                    default:
                        throw new StoregateExceptionMappingService().map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(),
                            EntityUtils.toString(response.getEntity())));
                }
            }
            catch(BackgroundException e) {
                throw new IOException(e);
            }
            finally {
                EntityUtils.consume(response.getEntity());
            }
        }
    }
    finally {
        close.set(true);
    }
}
 
Example 16
Source File: DeployControllerTest.java    From reposilite with Apache License 2.0 4 votes vote down vote up
private HttpResponse put(String uri, String username, String password, String content) throws IOException, AuthenticationException {
    HttpPut httpPut = new HttpPut(url(uri).toString());
    httpPut.setEntity(new StringEntity(content));
    httpPut.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), httpPut, null));
    return client.execute(httpPut);
}
 
Example 17
Source File: BasicHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 4 votes vote down vote up
private void addHeader(HttpPut httpput, String accessKey, String value) {
   	httpput.addHeader(accessKey, value);
}
 
Example 18
Source File: Communicator.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
public int sendPut(String data, String url) {
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    try {

        HttpPut request = new HttpPut(url);
        StringEntity params =new StringEntity(data,"UTF-8");
        params.setContentType("application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("Accept", "*/*");
        request.addHeader("Accept-Encoding", "gzip,deflate,sdch");
        request.addHeader("Accept-Language", "en-US,en;q=0.8");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        responseCode = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) {

            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

            String output;
            // System.out.println("Output from Server ...." + response.getStatusLine().getStatusCode() + "\n");
            while ((output = br.readLine()) != null) {
                // System.out.println(output);
            }
        }
        else{
        	logger.error("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

    }catch (Exception ex) {
        logger.warn("Error in processing request for data : " + data + " and url : " + url,ex);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return responseCode;

}
 
Example 19
Source File: PybossaCommunicator.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public int sendPut(String data, String url) {
    int responseCode = -1;
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPut request = new HttpPut(url);
        StringEntity params =new StringEntity(data,"UTF-8");
        params.setContentType("application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("Accept", "*/*");
        request.addHeader("Accept-Encoding", "gzip,deflate,sdch");
        request.addHeader("Accept-Language", "en-US,en;q=0.8");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);
        responseCode = response.getStatusLine().getStatusCode();
        if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 204) {

            BufferedReader br = new BufferedReader(
                    new InputStreamReader((response.getEntity().getContent())));

            String output;
           // System.out.println("Output from Server ...." + response.getStatusLine().getStatusCode() + "\n");
            while ((output = br.readLine()) != null) {
               // System.out.println(output);
            }
        }
        else{
            logger.error(response.getStatusLine().getStatusCode());

            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

    }catch (Exception ex) {
        logger.error("ex Code sendPut: " + ex);
        logger.error("url:" + url);
        logger.error("data:" + data);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return responseCode;

}
 
Example 20
Source File: BasicHttpClient.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 2 votes vote down vote up
/**
 * custom header for respective client
 *
 * @param httpput
 */
public void setHeader(HttpPut httpput) {
    httpput.addHeader("Accept", "application/json");
}