下面列出了org.apache.http.client.methods.HttpPut#addHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
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();
}
/**
* 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);
}
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();
}
/**
* 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());
}
}
}
/**
* 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);
}
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);
}
/**
* 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;
}
/**
* 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));
}
/**
* 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;
}
}
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;
}
public HttpPut updateTransport(String id)
{
HttpPut put = new HttpPut(createTransportUri(id,null));
put.addHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
return put;
}
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);
}
/**
* 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;
}
@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;
}
@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);
}
}
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);
}
private void addHeader(HttpPut httpput, String accessKey, String value) {
httpput.addHeader(accessKey, value);
}
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;
}
/**
* custom header for respective client
*
* @param httpput
*/
public void setHeader(HttpPut httpput) {
httpput.addHeader("Accept", "application/json");
}