下面列出了org.apache.http.client.methods.HttpPost#setHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String httpPOST(String url, Map<String, String> formParams, 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");
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : formParams.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpClient client = getClient();
HttpResponse response = client.execute(request);
//try {
return fetchResponse(response);
/*} finally {
request.releaseConnection();
client.getConnectionManager().shutdown();
}*/
}
@Test
public void testBatchUriEncoded() throws Exception {
final HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "%24batch"));
post.setHeader("Content-Type", "multipart/mixed;boundary=batch_98c1-8b13-36bb");
HttpEntity entity = new StringEntity(REQUEST_PAYLOAD);
post.setEntity(entity);
HttpResponse response = getHttpClient().execute(post);
assertNotNull(response);
assertEquals(202, response.getStatusLine().getStatusCode());
assertEquals("HTTP/1.1", response.getProtocolVersion().toString());
assertTrue(response.containsHeader("Content-Length"));
assertTrue(response.containsHeader("Content-Type"));
assertTrue(response.containsHeader("DataServiceVersion"));
assertTrue(response.getEntity().getContentType().getValue().matches(REG_EX));
assertNotNull(response.getEntity().getContent());
String body = StringHelper.inputStreamToString(response.getEntity().getContent(), true);
assertTrue(body.contains("Content-Id: mimeHeaderContentId1"));
assertTrue(body.contains("Content-Id: requestHeaderContentId1"));
assertTrue(body.contains("Content-Id: mimeHeaderContentId2"));
assertTrue(body.contains("Content-Id: requestHeaderContentId2"));
}
@Test
public void testContentIDReferencingfail() throws Exception {
final HttpPost post = new HttpPost(URI.create(getEndpoint().toString() + "$batch"));
post.setHeader("Content-Type", "multipart/mixed;boundary=" + BOUNDARY);
String body = StringHelper.inputStreamToStringCRLFLineBreaks(
this.getClass().getResourceAsStream("/basicBatchWithContentIdReferencingFail.batch"));
HttpEntity entity = new StringEntity(body);
post.setEntity(entity);
HttpResponse batchResponse = getHttpClient().execute(post);
assertNotNull(batchResponse);
assertEquals(202, batchResponse.getStatusLine().getStatusCode());
InputStream responseBody = batchResponse.getEntity().getContent();
String contentType = batchResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
List<BatchSingleResponse> responses = EntityProvider.parseBatchResponse(responseBody, contentType);
assertEquals("400", responses.get(0).getStatusCode());
assertEquals("Bad Request", responses.get(0).getStatusInfo());
assertEquals("201", responses.get(1).getStatusCode());
assertEquals("Created", responses.get(1).getStatusInfo());
assertEquals("404", responses.get(2).getStatusCode());
assertEquals("Not Found", responses.get(2).getStatusInfo());
assertEquals("200", responses.get(3).getStatusCode());
assertEquals("OK", responses.get(3).getStatusInfo());
}
private void login(String requestURI, CookieStore cookieStore) throws IOException {
HttpCoreContext httpContext = new HttpCoreContext();
HttpGet request = new HttpGet(requestURI);
// send an initial request, we are redirected to login page
String entityContent;
try (CloseableHttpResponse response = sendRequest(request, cookieStore, httpContext)) {
entityContent = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
}
// send credentials to login form
HttpPost post = new HttpPost(ActionURIUtils.getActionURIFromPageSource(entityContent));
List<NameValuePair> params = new LinkedList<>();
params.add(new BasicNameValuePair("username", "foo"));
params.add(new BasicNameValuePair("password", "password"));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(params));
try (CloseableHttpResponse response = sendRequest(post, cookieStore, httpContext)) {
Assert.assertThat("Expected successful login.", response.getStatusLine().getStatusCode(), is(equalTo(200)));
}
}
/**
* Post 方式请求 ,并返回HTTP_STATUS_CODE码
*
* @param String address 请求地址
* @param Map<String, Object> params 请求参数
* @return int
* @throws ClientProtocolException
* @throws IOException
*/
public int postReturnHttpCode(String address, Map<String, Object> params) throws ClientProtocolException,
IOException {
HttpPost httpPost = new HttpPost(address);
HttpResponse httpResponse = null;
try {
List<NameValuePair> data = buildPostData(params);
httpPost.setEntity(new UrlEncodedFormEntity(data, HTTP.UTF_8));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpPost.setHeader("User-Agent", agent);
httpResponse = httpClient.execute(httpPost);
return httpResponse.getStatusLine().getStatusCode();
} finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity()); //会自动释放连接
} catch (Exception e) {
}
}
}
}
public static String doHttpPost(final String url, final String requestBody) throws Exception {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(url);
httppost.setHeader(PacmanRuleConstants.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntity = new StringEntity(requestBody);
httppost.setEntity(jsonEntity);
HttpResponse httpresponse = client.execute(httppost);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
return EntityUtils.toString(httpresponse.getEntity());
} else {
throw new Exception("unable to execute post request because "
+ httpresponse.getStatusLine().getReasonPhrase());
}
} catch (Exception e) {
throw new RuleExecutionFailedExeption(e.getMessage());
}
}
public static String getConcept(JSONObject jjj)
throws UnsupportedEncodingException, IOException, ClientProtocolException {
HttpPost httppost = new HttpPost(vocubularyurl);
// httppost.setHeader("X-GWT-Permutation",
// "3DE824138FE65400740EC1816A73CACC");
httppost.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jjj.toString());
httppost.setEntity(se);
startTime = System.currentTimeMillis();
HttpResponse httpresponse = new DefaultHttpClient().execute(httppost);
endTime = System.currentTimeMillis();
System.out.println("statusCode:" + httpresponse.getStatusLine().getStatusCode());
System.out.println("Call API time (unit:millisecond):" + (endTime - startTime));
if (httpresponse.getStatusLine().getStatusCode() == 200) {
// System.out.println("succeed!");
String strResult = EntityUtils.toString(httpresponse.getEntity());
return strResult;
// httppost.
} else {
return null;
}
}
public static String httpPostMethodWithHeaders(String url,Map<String, Object> headers) throws Exception {
String json = null;
HttpPost post = new HttpPost(url);
CloseableHttpClient httpClient = null;
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue().toString());
}
}
try {
httpClient = getHttpClient();
CloseableHttpResponse res = httpClient.execute(post);
if (res.getStatusLine().getStatusCode() == 200) {
json = EntityUtils.toString(res.getEntity());
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return json;
}
private static void getPreDownloadLink() throws IOException {
//http://uploading.com/files/generate/?ajax
DefaultHttpClient d = new DefaultHttpClient();
HttpPost h = new HttpPost("http://uploading.com/files/generate/?ajax");
h.setHeader("Cookie", sidcookie + ";" + ucookie + ";" + timecookie + ";" + cachecookie);
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("name", file.getName()));
formparams.add(new BasicNameValuePair("size", String.valueOf(file.length())));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
h.setEntity(entity);
HttpResponse r = d.execute(h);
HttpEntity e = r.getEntity();
downloadlink = EntityUtils.toString(e);
fileID = parseResponse(downloadlink, "file_id\":\"", "\"");
downloadlink = parseResponse(downloadlink, "\"link\":\"", "\"");
System.out.println("File ID : " + fileID);
System.out.println("Download link : " + downloadlink);
}
@Test
public void shouldPrintMultilineRequestProperly() throws Exception {
// given
HttpPost postRequest = new HttpPost("http://google.pl/");
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
postRequest.setEntity(new UrlEncodedFormEntity(postParameters));
postRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
// when
Options options = Options.builder().targetPlatform(Platform.UNIX).useShortForm()
.printMultiliner().build();
// then
assertThat(new Http2Curl(options).generateCurl(postRequest),
equalTo(
"curl 'http://google.pl/' \\\n -H 'Content-Type: application/x-www-form-urlencoded' \\\n --data-binary 'param1=param1_value¶m2=param2_value' \\\n --compressed \\\n -k \\\n -v"));
}
private Map<String, Object> tokenRequest(App app, String authCodeOrRefreshToken, String redirectURI, String alias)
throws IOException {
String[] keys = SecurityUtils.getOAuthKeysForApp(app, oauthPrefix(alias));
String entity;
String scope = SecurityUtils.getSettingForApp(app, configKey("scope", alias), "");
if (redirectURI == null) {
entity = Utils.formatMessage(REFRESH_PAYLOAD, authCodeOrRefreshToken,
URLEncoder.encode(scope, "UTF-8"), keys[0], keys[1]);
} else {
entity = Utils.formatMessage(PAYLOAD, authCodeOrRefreshToken, Utils.urlEncode(redirectURI),
URLEncoder.encode(scope, "UTF-8"), keys[0], keys[1]);
}
String acceptHeader = SecurityUtils.getSettingForApp(app, configKey("accept_header", alias), "");
HttpPost tokenPost = new HttpPost(SecurityUtils.getSettingForApp(app, configKey("token_url", alias), ""));
tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
if (!StringUtils.isBlank(acceptHeader)) {
tokenPost.setHeader(HttpHeaders.ACCEPT, acceptHeader);
}
Map<String, Object> tokens = null;
try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
if (resp1 != null && resp1.getEntity() != null) {
tokens = jreader.readValue(resp1.getEntity().getContent());
EntityUtils.consumeQuietly(resp1.getEntity());
}
}
return tokens;
}
@Test
public void basicOTAForSingleUserAndExistingProject() throws Exception {
HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?user=" + getUserName() + "&project=My%20Dashboard");
post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));
String fileName = "test.bin";
InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
String path;
try (CloseableHttpResponse response = httpclient.execute(post)) {
assertEquals(200, response.getStatusLine().getStatusCode());
path = TestUtil.consumeText(response);
assertNotNull(path);
assertTrue(path.startsWith("/static"));
assertTrue(path.endsWith("bin"));
}
String responseUrl = "http://127.0.0.1:18080" + path;
verify(clientPair.hardwareClient.responseMock, after(500).never()).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
TestHardClient newHardwareClient = new TestHardClient("localhost", properties.getHttpPort());
newHardwareClient.start();
newHardwareClient.login(clientPair.token);
verify(newHardwareClient.responseMock, timeout(1000)).channelRead(any(), eq(ok(1)));
newHardwareClient.reset();
newHardwareClient.send("internal " + b("ver 0.3.1 h-beat 10 buff-in 256 dev Arduino cpu ATmega328P con W5100 build 111"));
verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(ok(1)));
verify(newHardwareClient.responseMock, timeout(500)).channelRead(any(), eq(internal(7777, "ota " + responseUrl)));
}
static void assertGreet(Path wildFlyHome, String uri, String user, String password, int responseCode,
String responseBody) throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
KeyStoreException, CertificateException, IOException {
try (CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(SecurityUtils.createBasicSocketFactory(wildFlyHome)).build()) {
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "text/xml");
request.setHeader("soapaction", "\"urn:greet\"");
if (user != null) {
String auth = user + ":" + password;
String authHeader = "Basic "
+ Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.ISO_8859_1));
request.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
}
request.setEntity(
new StringEntity(String.format(WS_MESSAGE_TEMPLATE, "Hi", "Joe"), StandardCharsets.UTF_8));
try (CloseableHttpResponse response = httpclient.execute(request)) {
final int actualCode = response.getStatusLine().getStatusCode();
Assert.assertEquals(responseCode, actualCode);
if (actualCode == 200) {
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity, StandardCharsets.UTF_8);
Assert.assertTrue(body.contains(responseBody));
}
}
}
}
/**
* Create Post Request with json body
*/
public HttpPost createPost(String uri, String data) {
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Content-Type", "application/json");
HttpEntity entity = new StringEntity(data, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
return httpPost;
}
/**
* 功能:请求一个url,得到返回的信息。
* @author 朱志杰 QQ:695520848
* Jul 2, 2013 6:04:59 PM
* @param url 需要请求的url。
* @param method 使用的方法,POST或者GET。
* @param argsMap ,当method为POST时,在这里传入post的参数信息。
* @param ContentType 文本类型,例如"text/html;charset=UTF-8".注意POST时会自动修改为"application/x-www-form-urlencoded"。
* @return String
* @throws IOException 请求IO异常
* @throws ClientProtocolException 请求客户端协议异常
*/
public String requestUrl(String url,String method,Map<String,String> argsMap,String ContentType) throws ClientProtocolException, IOException{
((DefaultHttpClient)httpclient).setCookieStore(cookieStore);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
//页面的返回信息。
String confirmResponse ="";
//POST请求
if("POST".equals(method.toUpperCase())){
HttpPost httpPost = new HttpPost(url);
//表单内容。
if(!CollectionUtil.isEmpty(argsMap)){
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
for(String key : argsMap.keySet()){
nvps.add(new BasicNameValuePair(key, argsMap.get(key)));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
confirmResponse=httpclient.execute(httpPost,responseHandler);
}else{
//get请求
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", ContentType);
confirmResponse=httpclient.execute(httpGet,responseHandler);
}
cookieStore=((DefaultHttpClient)httpclient).getCookieStore();
return confirmResponse;
}
public YouTrackResponse post(String path, String body) throws IOException {
HttpPost request = new HttpPost(host + path);
request.setHeader("Content-Type", CONTENT_TYPE);
if (body != null) {
request.setEntity(new StringEntity(body));
}
return call(request);
}
public HttpPost createPost(String uri, ServerConfig serverConfig) {
HttpPost post = new HttpPost(getServerUrl(serverConfig, uri));
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
return post;
}
private static void processAuthentication(HttpPost method, String username, String password) {
if (username != null && username.trim().length() > 0) {
method.setHeader("Authorization",
"Basic " + Base64.encode((username + ":" + password).getBytes()));
}
}
private String oozieSubmitJob( String user, String password, String request, int status ) throws IOException, URISyntaxException {
driver.getMock( "OOZIE" )
.expect()
.method( "POST" )
.pathInfo( "/v1/jobs" )
.respond()
.status( HttpStatus.SC_CREATED )
.content( driver.getResourceBytes( "oozie-jobs-submit-response.json" ) )
.contentType( "application/json" );
URL url = new URL( driver.getUrl( "OOZIE" ) + "/v1/jobs?action=start" + ( driver.isUseGateway() ? "" : "&user.name=" + user ) );
HttpHost targetHost = new HttpHost( url.getHost(), url.getPort(), url.getProtocol() );
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpClientContext context = HttpClientContext.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope( targetHost ),
new UsernamePasswordCredentials( user, password ) );
context.setCredentialsProvider( credsProvider );
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
// Generate BASIC scheme object and add it to the local auth cache
BasicScheme basicAuth = new BasicScheme();
authCache.put( targetHost, basicAuth );
// Add AuthCache to the execution context
context.setAuthCache( authCache );
HttpPost post = new HttpPost( url.toURI() );
// post.getParams().setParameter( "action", "start" );
StringEntity entity = new StringEntity( request, org.apache.http.entity.ContentType.create( "application/xml", StandardCharsets.UTF_8.name() ) );
post.setEntity( entity );
post.setHeader( "X-XSRF-Header", "ksdjfhdsjkfhds" );
HttpResponse response = client.execute( targetHost, post, context );
assertThat( response.getStatusLine().getStatusCode(), Matchers.is(status) );
String json = EntityUtils.toString( response.getEntity() );
// String json = given()
// .log().all()
// .auth().preemptive().basic( user, password )
// .queryParam( "action", "start" )
// .contentType( "application/xml;charset=UTF-8" )
// .content( request )
// .then()
// .log().all()
// .statusCode( status )
// .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
return JsonPath.from(json).getString( "id" );
}
@Repeat(iterations=2) // 2 times to make sure cleanup is complete and we can create the same collection
public void testCreateDelete() throws Exception {
switch (random().nextInt(3)) {
case 0:
CollectionAdminRequest.createCollection(collectionName, "conf", 2, 0, 4, 0)
.setMaxShardsPerNode(100)
.process(cluster.getSolrClient());
cluster.waitForActiveCollection(collectionName, 2, 8);
break;
case 1:
// Sometimes don't use SolrJ
String url = String.format(Locale.ROOT, "%s/admin/collections?action=CREATE&name=%s&collection.configName=%s&numShards=%s&tlogReplicas=%s&maxShardsPerNode=%s",
cluster.getRandomJetty(random()).getBaseUrl(),
collectionName, "conf",
2, // numShards
4, // tlogReplicas
100); // maxShardsPerNode
HttpGet createCollectionGet = new HttpGet(url);
HttpResponse httpResponse = cluster.getSolrClient().getHttpClient().execute(createCollectionGet);
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
cluster.waitForActiveCollection(collectionName, 2, 8);
break;
case 2:
// Sometimes use V2 API
url = cluster.getRandomJetty(random()).getBaseUrl().toString() + "/____v2/c";
String requestBody = String.format(Locale.ROOT, "{create:{name:%s, config:%s, numShards:%s, tlogReplicas:%s, maxShardsPerNode:%s}}",
collectionName, "conf",
2, // numShards
4, // tlogReplicas
100); // maxShardsPerNode
HttpPost createCollectionPost = new HttpPost(url);
createCollectionPost.setHeader("Content-type", "application/json");
createCollectionPost.setEntity(new StringEntity(requestBody));
httpResponse = cluster.getSolrClient().getHttpClient().execute(createCollectionPost);
assertEquals(200, httpResponse.getStatusLine().getStatusCode());
cluster.waitForActiveCollection(collectionName, 2, 8);
break;
}
boolean reloaded = false;
while (true) {
DocCollection docCollection = getCollectionState(collectionName);
assertNotNull(docCollection);
assertEquals("Expecting 2 shards",
2, docCollection.getSlices().size());
assertEquals("Expecting 4 relpicas per shard",
8, docCollection.getReplicas().size());
assertEquals("Expecting 8 tlog replicas, 4 per shard",
8, docCollection.getReplicas(EnumSet.of(Replica.Type.TLOG)).size());
assertEquals("Expecting no nrt replicas",
0, docCollection.getReplicas(EnumSet.of(Replica.Type.NRT)).size());
assertEquals("Expecting no pull replicas",
0, docCollection.getReplicas(EnumSet.of(Replica.Type.PULL)).size());
for (Slice s:docCollection.getSlices()) {
assertTrue(s.getLeader().getType() == Replica.Type.TLOG);
List<String> shardElectionNodes = cluster.getZkClient().getChildren(ZkStateReader.getShardLeadersElectPath(collectionName, s.getName()), null, true);
assertEquals("Unexpected election nodes for Shard: " + s.getName() + ": " + Arrays.toString(shardElectionNodes.toArray()),
4, shardElectionNodes.size());
}
assertUlogPresence(docCollection);
if (reloaded) {
break;
} else {
// reload
CollectionAdminResponse response = CollectionAdminRequest.reloadCollection(collectionName)
.process(cluster.getSolrClient());
assertEquals(0, response.getStatus());
waitForState("failed waiting for active colletion", collectionName, clusterShape(2, 8));
reloaded = true;
}
}
}