下面列出了org.apache.http.client.methods.HttpPost#addHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@When("^users upload data on a project$")
public void usersUploadDataOnAProject() throws IOException {
wireMockServer.start();
configureFor("localhost", wireMockServer.port());
stubFor(post(urlEqualTo(CREATE_PATH))
.withHeader("content-type", equalTo(APPLICATION_JSON))
.withRequestBody(containing("testing-framework"))
.willReturn(aResponse().withStatus(200)));
HttpPost request = new HttpPost("http://localhost:" + wireMockServer.port() + "/create");
StringEntity entity = new StringEntity(jsonString);
request.addHeader("content-type", APPLICATION_JSON);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
verify(postRequestedFor(urlEqualTo(CREATE_PATH))
.withHeader("content-type", equalTo(APPLICATION_JSON)));
wireMockServer.stop();
}
public static String httpsPostBody(String url, String jsonString) {
String content = null;
HttpPost post = new HttpPost(url);
try {
post.setConfig(requestConfig);
post.addHeader("Content-Type", "application/json");
post.setEntity(new StringEntity(jsonString,DEFAULT_CHARSET));
HttpResponse response = httpsClient.execute(post);
HttpEntity entity = response.getEntity();
content = getContent(entity,DEFAULT_CHARSET);
post.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return content;
}
@Test(groups = { "wso2.esb" }, description = "Sending a Message Via REST to check the order of the auth headers")
public void testAuthHeaderOrder() throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(getApiInvocationURL("stockquote") + "/order/");
httpPost.addHeader("WWW-Authenticate", "NTLM");
httpPost.addHeader("WWW-Authenticate", "Basic realm=\"BasicSecurityFilterProvider\"");
httpPost.addHeader("WWW-Authenticate", "ANTLM3");
httpPost.setEntity(new StringEntity("<request/>"));
httpClient.execute(httpPost);
String response = wireServer.getCapturedMessage();
Assert.assertNotNull(response);
Assert.assertTrue(response.contains(
"WWW-Authenticate: NTLM\r\nWWW-Authenticate: Basic realm=\"BasicSecurityFilterProvider\"\r\nWWW-Authenticate: ANTLM3"));
}
/**
* Send HTTP POST request to {@link #endpointUrl}, logins to HAC
*
* @throws IOException
* @throws ClientProtocolException
*/
protected void loginToHac() throws ClientProtocolException, IOException {
final HttpPost postRequest = new HttpPost(endpointUrl + Authentication.Path.LOGIN);
final Map<String, String> parameters = new HashMap<>();
parameters.put(Authentication.Parameters.USERNAME, username);
parameters.put(Authentication.Parameters.PASSWORD, password);
postRequest.addHeader(Meta.X_CSRF_TOKEN, csrfToken);
postRequest.setEntity(new UrlEncodedFormEntity(createParametersList(parameters)));
final HttpResponse response = httpClient.execute(postRequest, context);
final Header[] locationHeaders = response.getHeaders(Authentication.LOCATION_HEADER);
if (Meta.NOT_FOUND_STATUS_CODE == response.getStatusLine().getStatusCode()) {
throw new IOException(ErrorMessage.INVALID_HAC_URL);
} else if (locationHeaders.length > 0
&& locationHeaders[0].getValue().contains(Authentication.LOCATION_ERROR)) {
throw new IOException(ErrorMessage.WRONG_CREDENTIALS);
}
}
protected HttpResponse sendBatchCompressed(HttpPost httpPost, byte[] raw)
throws TransportException {
/*
* Write gzip data to Entity and set content encoding to gzip
*/
ByteArrayEntity entity = new ByteArrayEntity(raw, ContentType.DEFAULT_BINARY);
entity.setContentEncoding("gzip");
httpPost.addHeader(new BasicHeader("Accept-Encoding", "gzip"));
httpPost.setEntity(entity);
/*
* Make call
*/
HttpResponse resp = null;
try {
resp = this.client.execute(httpPost);
} catch (IOException e) {
throw new TransportException("failed to make call", e);
}
return resp;
}
@Test
public void authenticationEnabled_anonymous_forbidden() throws IOException {
Boolean defaultValue = jenkins.get(GitLabConnectionConfig.class).isUseAuthenticatedEndpoint();
assertTrue(defaultValue);
jenkins.getInstance().setAuthorizationStrategy(new GlobalMatrixAuthorizationStrategy());
URL jenkinsURL = jenkins.getURL();
FreeStyleProject project = jenkins.createFreeStyleProject("test");
GitLabPushTrigger trigger = mock(GitLabPushTrigger.class);
project.addTrigger(trigger);
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(jenkinsURL.toExternalForm() + "project/test");
request.addHeader("X-Gitlab-Event", "Push Hook");
request.setEntity(new StringEntity("{}"));
CloseableHttpResponse response = client.execute(request);
assertThat(response.getStatusLine().getStatusCode(), is(403));
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
@Override
public boolean addTorrent(String link, String name, String hash, Long size, float downloadLimit, float uploadLimit) throws IOException {
System.out.println("\u001b[37;1m [Info] \u001b[36m qBittorrent:\u001b[0m Adding torrent " + link.substring(0, link.indexOf("passkey") - 1) + " ...");
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://127.0.0.1:" + getPort() + "/api/v2/torrents/add");
httpPost.addHeader("User-Agent", "BoxHelper");
httpPost.addHeader("Host", "127.0.0.1:" + getPort());
httpPost.addHeader("Cookie", "SID=" + this.sessionID);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addTextBody("urls", link);
multipartEntityBuilder.addTextBody("dlLimit", (int)(downloadLimit * 1024 * 1024) + "");
multipartEntityBuilder.addTextBody("upLimit", (int)(uploadLimit * 1024 * 1024) + "");
httpPost.setEntity(multipartEntityBuilder.build());
httpClient.execute(httpPost);
httpClient.close();
boolean added =recheck(hash, name, size, TorrentState.DOWNLOADING);
if (added) {
System.out.println("\u001b[37;1m [Info] \u001b[36m qBittorrent:\u001b[0m Successfully added torrent " + link.substring(0, link.indexOf("passkey") - 1) + " .");
acquireTorrents(TorrentState.DOWNLOADING);
for (Object torrent:this.downloadingTorrents) {
if (((QbittorrentTorrents) torrent).getName().contains(name) || ((QbittorrentTorrents) torrent).getName().contains(name.replaceAll("\\s", "\\."))) {
hash = ((QbittorrentTorrents) torrent).getHash();
break;
}
}
}
else System.out.println("\u001b[33;1m [Warning]\u001b[36m qBittorrent:\u001b[0m Cannot add torrent " + link.substring(0, link.indexOf("passkey") - 1) + " . Retry later...");
return added;
}
public static HttpResponse httpPOSTReturnResponse(String url, String type, String data, Map<String, String> headers) throws Exception {
HttpPost request = new HttpPost(url);
if (headers != null) {
for (Entry<String, String> header : headers.entrySet()) {
request.setHeader(header.getKey(), header.getValue());
}
}
request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
StringEntity params = new StringEntity(data, "utf-8");
request.addHeader("content-type", type);
request.setEntity(params);
HttpClient client = getClient();
HttpResponse response = client.execute(request);
return response;
}
/**
* Posts the given String to the given TestRails end-point
* @param apiCall The end-point that expects to receive the entities (e.g. "add_result")
* @param urlParams The remainder of the URL required for the POST. It is up to you to get this part right
* @param entity The BaseEntity object to use at the POST body
* @return The Content of the HTTP Response
*/
private HttpResponse postRESTBody(String apiCall, String urlParams, BaseEntity entity) {
HttpClient httpClient = new DefaultHttpClient();
String completeUrl = buildRequestURL( apiCall, urlParams );
try {
HttpPost request = new HttpPost( completeUrl );
String authentication = utils.encodeAuthenticationBase64(username, password);
request.addHeader("Authorization", "Basic " + authentication);
request.addHeader("Content-Type", "application/json");
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
byte[] body = mapper.writeValueAsBytes(entity);
request.setEntity(new ByteArrayEntity(body));
HttpResponse response = executeRequestWithRetry(request, 2);
if (response.getStatusLine().getStatusCode() != 200) {
Error error = JSONUtils.getMappedJsonObject(Error.class, utils.getContentsFromHttpResponse(response));
log.error("Response code: {}", response.getStatusLine().getStatusCode());
log.error("TestRails reported an error message: {}", error.getError());
request.addHeader("Encoding", "UTF-8");
}
return response;
}
catch (IOException e) {
log.error(String.format("An IOException was thrown while trying to process a REST Request against URL: [%s]", completeUrl), e.toString());
throw new RuntimeException(String.format("Connection is null, check URL: %s", completeUrl));
} finally {
httpClient.getConnectionManager().shutdown();
}
}
public <T extends GeneratedMessage> HttpUriRequest newRequest(
String url,
String container,
String bundle,
String cloudKitUserId,
String cloudKitToken,
String uuid,
List<T> protobufs
) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
protobufs.forEach(message -> {
try {
message.writeDelimitedTo(baos);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
});
ByteArrayEntity byteArrayEntity = new ByteArrayEntity(baos.toByteArray());
HttpPost post = new HttpPost(url);
post.setHeader(Headers.XAPPLEREQUESTUUID.header(uuid));
post.setHeader(Headers.XCLOUDKITUSERID.header(cloudKitUserId));
post.setHeader(Headers.XCLOUDKITAUTHTOKEN.header(cloudKitToken));
post.setHeader(Headers.XCLOUDKITCONTAINERID.header(container));
post.setHeader(Headers.XCLOUDKITBUNDLEID.header(bundle));
post.setHeader(HttpHeaders.ACCEPT, "application/x-protobuf");
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-protobuf; desc=\"https://p33-ckdatabase.icloud.com:443/static/protobuf/CloudDB/CloudDBClient.desc\"; messageType=RequestOperation; delimited=true");
post.addHeader(headers.get(Headers.USERAGENT));
post.addHeader(headers.get(Headers.XCLOUDKITPROTOCOLVERSION));
post.addHeader(headers.get(Headers.XMMECLIENTINFO));
post.setEntity(byteArrayEntity);
return post;
}
private static void fileUpload() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://upbooth.com/uploadHandler.php?r=upbooth.com&p=http?aff=1db2f3b654350bf4");
httppost.addHeader("Cookie", fileHostingCookie);
file = new File("c:/Dinesh/Naruto_Face.jpg");
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(file);
String cookie = fileHostingCookie.substring(fileHostingCookie.indexOf("=") + 1);
cookie = cookie.substring(0, cookie.indexOf(";"));
System.out.println(cookie);
mpEntity.addPart("=_sessionid", new StringBody(cookie));
mpEntity.addPart("files[]", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
System.out.println("Now uploading your file into upbooth.com");
HttpResponse response = httpclient.execute(httppost);
// HttpEntity resEntity = response.getEntity();
String uploadresponse = EntityUtils.toString(response.getEntity());
System.out.println(response.getStatusLine());
// if (resEntity != null) {
// uploadresponse = EntityUtils.toString(resEntity);
// }
//
System.out.println("Upload response : " + uploadresponse);
String downloadlink = parseResponse(uploadresponse, "\"url\":\"", "\"");
downloadlink = downloadlink.replaceAll("\\\\", "");
String deletelink = parseResponse(uploadresponse, "\"delete_url\":\"", "\"");
deletelink = deletelink.replaceAll("\\\\", "");
System.out.println("Download link : " + downloadlink);
System.out.println("Delete link : " + deletelink);
}
@Test
public void should400OnPOSTWithGremlinJsonEndcodedBodyWithNoGremlinKey() throws Exception {
final CloseableHttpClient httpclient = HttpClients.createDefault();
final HttpPost httppost = new HttpPost(TestClientFactory.createURLString());
httppost.addHeader("Content-Type", "application/json");
httppost.setEntity(new StringEntity("{\"gremadfadflin\":\"1-1\"}", Consts.UTF_8));
try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
assertEquals(400, response.getStatusLine().getStatusCode());
}
}
public String httpPostRequest(String uriString, String extractedText) throws IOException {
URI uri = URI.create(uriString);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Content-Type", "text/plain");
HttpEntity reqEntity = EntityBuilder.create().setText(URLEncoder.encode(extractedText, "UTF-8")).build();
httpPost.setEntity(reqEntity);
String responseBody = httpClient.execute(httpPost, this.responseHandler);
return responseBody;
}
/**
* 带证书的POST提交
* @param certPath
* @param url
* @param requestBody
* @return
*/
public static String doPostOfCert(String mchId, String certPath, String url, String requestBody) {
try {
CloseableHttpClient closeableHttpClient = HttpClientUtil.closeableHttpClientOfCert(certPath, mchId);
HttpPost httpPost = new HttpPost(url);
StringEntity postEntity = new StringEntity(requestBody, Charset.forName(StandardCharsets.UTF_8.name()));
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(postEntity);
HttpResponse response = closeableHttpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, Charset.forName(StandardCharsets.UTF_8.name()));
} catch (Exception e) {
throw new RuntimeException("执行请求失败!" + e.getMessage());
}
}
private static HttpPost addPageHttpPost(String confluenceRestApiEndpoint, PagePayload pagePayload) {
HttpPost postRequest = new HttpPost(confluenceRestApiEndpoint + "/content");
postRequest.setEntity(httpEntityWithJsonPayload(pagePayload));
postRequest.addHeader(APPLICATION_JSON_UTF8_HEADER);
return postRequest;
}
/**
* 初始化httpPost 对httpPost添加请求头信息
* @param httpPost
*/
private void initHttpPost(HttpPost httpPost) {
// 添加验证信息
httpPost.addHeader("Authorization", "Basic " + Base64Coder.encodeString(appKey + ":" + masterSecret));
httpPost.addHeader("Accept-Charset", "UTF-8");
httpPost.addHeader("Charset", "UTF-8");
httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
}
public static HttpResponse doPost(String url, Object json, String user, String password) throws IOException {
String restUrl = getRestEndPoint(url);
log.info("Sending HTTP POST request: " + restUrl);
client = new DefaultHttpClient();
post = new HttpPost(restUrl);
post.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password),
Charset.defaultCharset().toString(), false));
post.setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
client.getConnectionManager().closeExpiredConnections();
HttpResponse response = client.execute(post);
return response;
}
public static void create(String REST_URI,
String did,
String accesskey,
String secretkey,
Long startdate,
Long enddate,
String certificateProfileName,
Integer version,
String status,
String notes,
String policy) throws Exception
{
String apiversion = "2.0";
CreateFidoPolicyRequest cfpr = new CreateFidoPolicyRequest();
cfpr.setStartDate(startdate);
if (enddate != null)
cfpr.setEndDate(enddate);
cfpr.setCertificateProfileName(certificateProfileName);
cfpr.setVersion(version);
cfpr.setStatus(status);
cfpr.setNotes(notes);
cfpr.setPolicy(policy);
ObjectWriter ow = new ObjectMapper().writer();
String json = ow.writeValueAsString(cfpr);
ContentType mimetype = ContentType.APPLICATION_JSON;
StringEntity body = new StringEntity(json, mimetype);
String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
String contentSHA = common.calculateSha256(json);
String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.CREATE_POLICY_ENDPOINT;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(resourceLoc);
httpPost.setEntity(body);
String requestToHmac = httpPost.getMethod() + "\n"
+ contentSHA + "\n"
+ mimetype.getMimeType() + "\n"
+ currentDate + "\n"
+ apiversion + "\n"
+ httpPost.getURI().getPath();
String hmac = common.calculateHMAC(secretkey, requestToHmac);
httpPost.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
httpPost.addHeader("strongkey-content-sha256", contentSHA);
httpPost.addHeader("Content-Type", mimetype.getMimeType());
httpPost.addHeader("Date", currentDate);
httpPost.addHeader("strongkey-api-version", apiversion);
// Make API rest call and get response from the server
System.out.println("\nCalling create policy @ " + resourceLoc);
CloseableHttpResponse response = httpclient.execute(httpPost);
String result;
try {
StatusLine responseStatusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
EntityUtils.consume(entity);
switch (responseStatusLine.getStatusCode()) {
case 200:
System.out.println(" Response : " + result);
break;
case 401:
System.out.println("Error during create policy : 401 HMAC Authentication Failed");
return;
case 404:
System.out.println("Error during create policy : 404 Resource not found");
return;
case 400:
case 500:
default:
System.out.println("Error during create policy : " + responseStatusLine.getStatusCode() + " " + result);
return;
}
} finally {
response.close();
}
System.out.println("Result of create policy: " + result);
}
static KustoOperationResult post(String url, String payload, InputStream stream, Integer timeoutMs, HashMap<String, String> headers, boolean leaveOpen) throws DataServiceException, DataClientException {
HttpClient httpClient;
if (timeoutMs != null) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutMs).build();
httpClient = HttpClientBuilder.create().useSystemProperties().setDefaultRequestConfig(requestConfig).build();
} else {
httpClient = HttpClients.createSystem();
}
// TODO: maybe remove this as the stream closes by the httpClient anyway
try (InputStream streamToClose = (stream != null && !leaveOpen) ? stream : null) {
URL cleanUrl = new URL(url);
URI uri = new URI(cleanUrl.getProtocol(), cleanUrl.getUserInfo(), cleanUrl.getHost(), cleanUrl.getPort(), cleanUrl.getPath(), cleanUrl.getQuery(), cleanUrl.getRef());
// Request parameters and other properties.
HttpEntity requestEntity = (stream == null) ? new StringEntity(payload, ContentType.APPLICATION_JSON)
: new InputStreamEntity(stream);
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(requestEntity);
httpPost.addHeader("Accept-Encoding", "gzip,deflate");
for (HashMap.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
// Execute and get the response.
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StatusLine statusLine = response.getStatusLine();
String responseContent = EntityUtils.toString(entity);
if (statusLine.getStatusCode() == 200) {
return new KustoOperationResult(responseContent, url.endsWith("v2/rest/query") ? "v2" : "v1");
}
else {
throw new DataServiceException(url, "Error in post request", new DataWebException(responseContent, response));
}
}
} catch (JSONException | IOException | URISyntaxException | KustoServiceError e) {
throw new DataClientException(url, "Error in post request", e);
}
return null;
}