org.apache.http.client.methods.HttpPut#addHeader()源码实例Demo

下面列出了org.apache.http.client.methods.HttpPut#addHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ZTuoExchange_framework   文件: CaiPiaoHttpUtils.java
/**
 * 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);
   }
 
源代码2 项目: java-client-api   文件: ConnectedRESTQA.java
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();
}
 
源代码3 项目: frpMgr   文件: HttpUtils.java
/**
 * 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);
   }
 
源代码4 项目: java-client-api   文件: ClientApiFunctionalTest.java
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();
}
 
源代码5 项目: stocator   文件: SwiftOutputStream.java
/**
 * 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());
    }
  }
}
 
源代码6 项目: charging_pile_cloud   文件: AliHttpUtils.java
/**
 * 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);
}
 
源代码7 项目: amforeas   文件: AmforeasRestClient.java
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;
}
 
源代码9 项目: api-gateway-demo-sign-java   文件: HttpUtil.java
/**
 * 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));
}
 
源代码10 项目: spring-boot-study   文件: HttpRestUtils.java
/**
     * 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;
        }
    }
 
源代码11 项目: product-ei   文件: BPMNTestUtils.java
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;
}
 
源代码12 项目: devops-cm-client   文件: TransportRequestBuilder.java
public HttpPut updateTransport(String id)
{
  
  HttpPut put = new HttpPut(createTransportUri(id,null));
  put.addHeader(HttpHeaders.CONTENT_TYPE, "application/xml");
  return put;

}
 
源代码13 项目: BotLibre   文件: Utils.java
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);
}
 
源代码14 项目: reef   文件: HDInsightInstance.java
/**
 * 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;
}
 
源代码15 项目: AIDR   文件: PybossaCommunicator.java
@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;

}
 
源代码16 项目: cyberduck   文件: StoregateMultipartWriteFeature.java
@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);
    }
}
 
源代码17 项目: reposilite   文件: DeployControllerTest.java
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);
}
 
源代码19 项目: AIDR   文件: Communicator.java
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");
}