Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#addRequestHeader()
The following examples show how to use
org.apache.commons.httpclient.methods.PostMethod#addRequestHeader() .
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: RestClient.java From maven-framework-project with MIT License | 7 votes |
public Book getBook(String bookName) throws Exception { String output = null; try{ String url = "http://localhost:8080/bookservice/getbook/"; url = url + URLEncoder.encode(bookName, "UTF-8"); HttpClient client = new HttpClient(); PostMethod mPost = new PostMethod(url); client.executeMethod( mPost ); Header mtHeader = new Header(); mtHeader.setName("content-type"); mtHeader.setValue("application/x-www-form-urlencoded"); mtHeader.setName("accept"); mtHeader.setValue("application/xml"); mPost.addRequestHeader(mtHeader); client.executeMethod(mPost); output = mPost.getResponseBodyAsString( ); mPost.releaseConnection( ); System.out.println("out : " + output); }catch(Exception e){ throw new Exception("Exception in retriving group page info : " + e); } return null; }
Example 2
Source File: HttpUtil.java From OfficeAutomatic-System with Apache License 2.0 | 6 votes |
public static String sendPost(String urlParam) throws HttpException, IOException { // 创建httpClient实例对象 HttpClient httpClient = new HttpClient(); // 设置httpClient连接主机服务器超时时间:15000毫秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000); // 创建post请求方法实例对象 PostMethod postMethod = new PostMethod(urlParam); // 设置post请求超时时间 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000); postMethod.addRequestHeader("Content-Type", "application/json"); httpClient.executeMethod(postMethod); String result = postMethod.getResponseBodyAsString(); postMethod.releaseConnection(); return result; }
Example 3
Source File: VmRuntimeJettyKitchenSink2Test.java From appengine-java-vm-runtime with Apache License 2.0 | 6 votes |
/** * Test that blob upload requests are intercepted by the blob upload filter. * * @throws Exception */ public void testBlobUpload() throws Exception { String postData = "--==boundary\r\n" + "Content-Type: message/external-body; " + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n" + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n" + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n" + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--"; HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString()); blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\""); blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true"); blobPost.setRequestBody(postData); int httpCode = httpClient.executeMethod(blobPost); assertEquals(302, httpCode); Header redirUrl = blobPost.getResponseHeader("Location"); assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0", redirUrl.getValue()); }
Example 4
Source File: ZeppelinServerMock.java From zeppelin with Apache License 2.0 | 6 votes |
private static String getCookie(String user, String password) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(URL + "/login"); postMethod.addRequestHeader("Origin", URL); postMethod.setParameter("password", password); postMethod.setParameter("userName", user); httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); Pattern pattern = Pattern.compile("JSESSIONID=([a-zA-Z0-9-]*)"); Header[] setCookieHeaders = postMethod.getResponseHeaders("Set-Cookie"); String jsessionId = null; for (Header setCookie : setCookieHeaders) { java.util.regex.Matcher matcher = pattern.matcher(setCookie.toString()); if (matcher.find()) { jsessionId = matcher.group(1); } } if (jsessionId != null) { return jsessionId; } else { return StringUtils.EMPTY; } }
Example 5
Source File: HttpStatsReporterService.java From otroslogviewer with Apache License 2.0 | 6 votes |
@Override public void sendStats(Map<String, Long> stats, String uuid, String olvVersion, String javaVersion) { String r = stats .entrySet() .stream() .sorted(Comparator.comparing(Map.Entry::getKey)) .map(kv -> kv.getKey() + "=" + kv.getValue()).collect(Collectors.joining("\n")); HttpClient httpClient = new HttpClient(); PostMethod method = new PostMethod(SEND_URL); try { method.setRequestEntity(new StringRequestEntity(r, "text/plain", "UTF-8")); method.addRequestHeader("uuid", uuid); method.addRequestHeader("olvVersion", olvVersion); method.addRequestHeader("javaVersion", javaVersion); httpClient.executeMethod(method); } catch (Exception e) { //User is not interested in issues with sending report LOGGER.warn("Can't send stats to server", e); } }
Example 6
Source File: SecurityGroupHttpClient.java From cloudstack with Apache License 2.0 | 5 votes |
public HashMap<String, Pair<Long, Long>> sync(String vmName, Long vmId, String agentIp) { HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>(); PostMethod post = new PostMethod(String.format("http://%s:%s/", agentIp, getPort())); try { post.addRequestHeader("command", "sync"); if (httpClient.executeMethod(post) != 200) { logger.debug(String.format("echoing baremetal security group agent on %s got error: %s", agentIp, post.getResponseBodyAsString())); } else { String res = post.getResponseBodyAsString(); // res = ';'.join([vmName, vmId, seqno]) String[] rulelogs = res.split(","); if (rulelogs.length != 6) { logger.debug(String.format("host[%s] returns invalid security group sync document[%s], reset rules", agentIp, res)); states.put(vmName, new Pair<Long, Long>(vmId, -1L)); return states; } Pair<Long, Long> p = new Pair<Long, Long>(Long.valueOf(rulelogs[1]), Long.valueOf(rulelogs[5])); states.put(rulelogs[0], p); return states; } } catch (SocketTimeoutException se) { logger.warn(String.format("unable to sync security group rules on host[%s], %s", agentIp, se.getMessage())); } catch (Exception e) { logger.warn(String.format("unable to sync security group rules on host[%s]", agentIp), e); } finally { if (post != null) { post.releaseConnection(); } } return states; }
Example 7
Source File: SecurityGroupHttpClient.java From cloudstack with Apache License 2.0 | 5 votes |
public boolean echo(String agentIp, long l, long m) { boolean ret = false; int count = 1; while (true) { try { Thread.sleep(m); count++; } catch (InterruptedException e1) { logger.warn("", e1); break; } PostMethod post = new PostMethod(String.format("http://%s:%s/", agentIp, getPort())); try { post.addRequestHeader("command", "echo"); if (httpClient.executeMethod(post) != 200) { logger.debug(String.format("echoing baremetal security group agent on %s got error: %s", agentIp, post.getResponseBodyAsString())); } else { ret = true; } break; } catch (Exception e) { if (count*m >= l) { logger.debug(String.format("ping security group agent on vm[%s] timeout after %s minutes, starting vm failed, count=%s", agentIp, TimeUnit.MILLISECONDS.toSeconds(l), count)); break; } else { logger.debug(String.format("Having pinged security group agent on vm[%s] %s times, continue to wait...", agentIp, count)); } } finally { if (post != null) { post.releaseConnection(); } } } return ret; }
Example 8
Source File: FileUploadWithAttachmentUtil.java From product-es with Apache License 2.0 | 5 votes |
/** * This method uploads a content-type asset (ex: wsdl,policy,wadl,swagger) * to a running G-Reg instance * * @param filePath The absolute path of the file * @param fileVersion Version of the file * @param fileName Name of the file * @param shortName Asset shortname mentioned in the RXT * @param cookieHeader Session cookie * @throws IOException */ public static PostMethod uploadContentTypeAssets(String filePath, String fileVersion, String fileName, String shortName, String cookieHeader, String apiUrl) throws IOException { File file = new File(filePath); //The api implementation requires fileUpload name in the format //of shortname_file (ex: wsdl_file) FilePart fp = new FilePart(shortName + "_file", file); fp.setContentType(MediaType.TEXT_PLAIN); String version = fileVersion; String name = fileName; StringPart sp1 = new StringPart("file_version", version); sp1.setContentType(MediaType.TEXT_PLAIN); StringPart sp2 = new StringPart(shortName + "_file_name", name); sp2.setContentType(MediaType.TEXT_PLAIN); //Set file parts and string parts together final Part[] part = {fp, sp1, sp2}; HttpClient httpClient = new HttpClient(); PostMethod httpMethod = new PostMethod(apiUrl); httpMethod.addRequestHeader("Cookie", cookieHeader); httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON); httpMethod.setRequestEntity( new MultipartRequestEntity(part, httpMethod.getParams()) ); httpClient.executeMethod(httpMethod); return httpMethod; }
Example 9
Source File: UserMgmtITCase.java From olat with Apache License 2.0 | 5 votes |
@Test public void testPortrait() throws IOException, URISyntaxException { final URL portraitUrl = RepositoryEntriesITCase.class.getResource("portrait.jpg"); assertNotNull(portraitUrl); final File portrait = new File(portraitUrl.toURI()); final HttpClient c = loginWithCookie("rest-one", "A6B7C8"); // upload portrait final String request = "/users/" + id1.getKey() + "/portrait"; final PostMethod method = createPost(request, MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.MULTIPART_FORM_DATA); final Part[] parts = { new FilePart("file", portrait), new StringPart("filename", "portrait.jpg") }; method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams())); final int code = c.executeMethod(method); assertEquals(code, 200); method.releaseConnection(); // check if big and small portraits exist final DisplayPortraitManager dps = DisplayPortraitManager.getInstance(); final File uploadDir = dps.getPortraitDir(id1); assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_SMALL_FILENAME).exists()); assertTrue(new File(uploadDir, DisplayPortraitManager.PORTRAIT_BIG_FILENAME).exists()); // check get portrait final String getRequest = "/users/" + id1.getKey() + "/portrait"; final GetMethod getMethod = createGet(getRequest, MediaType.APPLICATION_OCTET_STREAM, true); final int getCode = c.executeMethod(getMethod); assertEquals(getCode, 200); final InputStream in = getMethod.getResponseBodyAsStream(); int b = 0; int count = 0; while ((b = in.read()) > -1) { count++; } assertEquals(-1, b);// up to end of file assertTrue(count > 1000);// enough bytes method.releaseConnection(); }
Example 10
Source File: OlatJerseyTestCase.java From olat with Apache License 2.0 | 5 votes |
public PostMethod createPost(final URI requestURI, final String accept, final boolean cookie) { final PostMethod method = new PostMethod(requestURI.toString()); if (cookie) { method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); } if (StringHelper.containsNonWhitespace(accept)) { method.addRequestHeader("Accept", accept); } return method; }
Example 11
Source File: CatalogITCase.java From olat with Apache License 2.0 | 5 votes |
@Test public void testUpdateCatalogEntryJson() throws IOException { final HttpClient c = loginWithCookie("administrator", "olat"); final CatalogEntryVO entry = new CatalogEntryVO(); entry.setName("Entry-1-b"); entry.setDescription("Entry-description-1-b"); entry.setType(CatalogEntry.TYPE_NODE); final String entity = stringuified(entry); final URI uri = UriBuilder.fromUri(getContextURI()).path("catalog").path(entry1.getKey().toString()).build(); final PostMethod method = createPost(uri, MediaType.APPLICATION_JSON, true); method.addRequestHeader("Content-Type", MediaType.APPLICATION_JSON); final RequestEntity requestEntity = new StringRequestEntity(entity, MediaType.APPLICATION_JSON, "UTF-8"); method.setRequestEntity(requestEntity); final int code = c.executeMethod(method); assertEquals(200, code); final String body = method.getResponseBodyAsString(); method.releaseConnection(); final CatalogEntryVO vo = parse(body, CatalogEntryVO.class); assertNotNull(vo); final CatalogEntry updatedEntry = catalogService.loadCatalogEntry(entry1); assertEquals("Entry-1-b", updatedEntry.getName()); assertEquals("Entry-description-1-b", updatedEntry.getDescription()); }
Example 12
Source File: OlatJerseyTestCase.java From olat with Apache License 2.0 | 5 votes |
public PostMethod createPost(final URI requestURI, final String accept, final boolean cookie) { final PostMethod method = new PostMethod(requestURI.toString()); if (cookie) { method.getParams().setCookiePolicy(CookiePolicy.RFC_2109); } if (StringHelper.containsNonWhitespace(accept)) { method.addRequestHeader("Accept", accept); } return method; }
Example 13
Source File: SecurityGroupHttpClient.java From cloudstack with Apache License 2.0 | 5 votes |
public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) { PostMethod post = new PostMethod(String.format( "http://%s:%s", agentIp, getPort())); try { SecurityGroupVmRuleSet rset = new SecurityGroupVmRuleSet(); rset.getEgressRules().addAll(generateRules(cmd.getEgressRuleSet())); rset.getIngressRules().addAll( generateRules(cmd.getIngressRuleSet())); rset.setVmName(cmd.getVmName()); rset.setVmIp(cmd.getGuestIp()); rset.setVmMac(cmd.getGuestMac()); rset.setVmId(cmd.getVmId()); rset.setSignature(cmd.getSignature()); rset.setSequenceNumber(cmd.getSeqNum()); Marshaller marshaller = context.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(rset, writer); String xmlContents = writer.toString(); logger.debug(xmlContents); post.addRequestHeader("command", "set_rules"); StringRequestEntity entity = new StringRequestEntity(xmlContents); post.setRequestEntity(entity); if (httpClient.executeMethod(post) != 200) { return new SecurityGroupRuleAnswer(cmd, false, post.getResponseBodyAsString()); } else { return new SecurityGroupRuleAnswer(cmd); } } catch (Exception e) { return new SecurityGroupRuleAnswer(cmd, false, e.getMessage()); } finally { if (post != null) { post.releaseConnection(); } } }
Example 14
Source File: PaypalRequest.java From development with Apache License 2.0 | 5 votes |
/** * * @param doc * Document with body info * @param route * Pay or Preapproval * @return the PostMethod to be invoked * @throws TransformerException * on bad xml input or transformer exceptions */ private PostMethod createPostMethod(Document doc, String route) throws TransformerException { final PostMethod postMethod = new PostMethod(PAYPAL_URL + '/' + route); // communication format postMethod.addRequestHeader("X-PAYPAL-REQUEST-DATA-FORMAT", "XML"); postMethod.addRequestHeader("X-PAYPAL-RESPONSE-DATA-FORMAT", "XML"); // authentication info postMethod.addRequestHeader("X-PAYPAL-SECURITY-USERID", "mercha_1310720134_biz_api1.est.fujitsu.com"); postMethod.addRequestHeader("X-PAYPAL-SECURITY-PASSWORD", "1310720175"); postMethod.addRequestHeader("X-PAYPAL-SECURITY-SIGNATURE", "AlTG0c2puvFWih-1mR5Tn9-Pbx6MAyndXBaCr0Cmgec8UBYC7Kty76vJ"); postMethod.addRequestHeader("X-PAYPAL-APPLICATION-ID", "APP-80W284485P519543T"); postMethod.addRequestHeader("X-PAYPAL-DEVICE-IPADDRESS", remoteIpAddr); try { postMethod.setRequestEntity(new StringRequestEntity( getDocAsString(doc), "text/xml", "UTF-8")); } catch (UnsupportedEncodingException ex) { // UTF-8 is always supported, so this exception should never been // thrown throw new RuntimeException(ex); } return postMethod; }
Example 15
Source File: FileUploadWithAttachmentUtil.java From product-es with Apache License 2.0 | 5 votes |
/** * This method uploads a content-type asset (ex: wsdl,policy,wadl,swagger) * to a running G-Reg instance * * @param filePath The absolute path of the file * @param fileVersion Version of the file * @param fileName Name of the file * @param shortName Asset shortname mentioned in the RXT * @param cookieHeader Session cookie * @throws IOException */ public static PostMethod uploadContentTypeAssets(String filePath, String fileVersion, String fileName, String shortName, String cookieHeader, String apiUrl) throws IOException { File file = new File(filePath); //The api implementation requires fileUpload name in the format //of shortname_file (ex: wsdl_file) FilePart fp = new FilePart(shortName + "_file", file); fp.setContentType(MediaType.TEXT_PLAIN); String version = fileVersion; String name = fileName; StringPart sp1 = new StringPart("file_version", version); sp1.setContentType(MediaType.TEXT_PLAIN); StringPart sp2 = new StringPart(shortName + "_file_name", name); sp2.setContentType(MediaType.TEXT_PLAIN); //Set file parts and string parts together final Part[] part = {fp, sp1, sp2}; HttpClient httpClient = new HttpClient(); PostMethod httpMethod = new PostMethod(apiUrl); httpMethod.addRequestHeader("Cookie", cookieHeader); httpMethod.addRequestHeader("Accept", MediaType.APPLICATION_JSON); httpMethod.setRequestEntity( new MultipartRequestEntity(part, httpMethod.getParams()) ); httpClient.executeMethod(httpMethod); return httpMethod; }
Example 16
Source File: HttpClientUtil.java From spider with GNU General Public License v3.0 | 5 votes |
public String post(String postURL, Map<String, String> partam, String cookies) throws IOException { // clearCookies(); PostMethod p = new PostMethod(postURL); for (String key : partam.keySet()) { if (partam.get(key) != null) { p.setParameter(key, partam.get(key)); } } if (StringUtils.isNotEmpty(cookies)) { p.addRequestHeader("cookie", cookies); } hc.executeMethod(p); return p.getResponseBodyAsString(); }
Example 17
Source File: CSP.java From scim2-compliance-test-suite with Apache License 2.0 | 5 votes |
public String getAccessTokenUserPass() { if (!StringUtils.isEmpty(this.oAuth2AccessToken)) { return this.oAuth2AccessToken; } if (StringUtils.isEmpty(this.username) || StringUtils.isEmpty(this.password) && StringUtils.isEmpty(this.oAuth2AuthorizationServer) || StringUtils.isEmpty(this.oAuth2ClientId) || StringUtils.isEmpty(this.oAuth2ClientSecret)) { return ""; } try { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(true); // post development PostMethod method = new PostMethod(this.getOAuthAuthorizationServer()); method.setRequestHeader(new Header("Content-type", "application/x-www-form-urlencoded")); method.addRequestHeader("Authorization", "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes())); NameValuePair[] body = new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password), new NameValuePair("client_id", oAuth2ClientId), new NameValuePair("client_secret", oAuth2ClientSecret), new NameValuePair("grant_type", oAuth2GrantType) }; method.setRequestBody(body); int responseCode = client.executeMethod(method); String responseBody = method.getResponseBodyAsString(); if (responseCode != 200) { throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer() + ", got response code " + responseCode); } JSONObject accessResponse = new JSONObject(responseBody); accessResponse.getString("access_token"); return (this.oAuth2AccessToken = accessResponse.getString("access_token")); } catch (Exception e) { throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e); } }
Example 18
Source File: HttpClientUtil.java From Gather-Platform with GNU General Public License v3.0 | 5 votes |
public String post(String postURL, Map<String, String> partam, String cookies) throws IOException { // clearCookies(); PostMethod p = new PostMethod(postURL); for (String key : partam.keySet()) { if (partam.get(key) != null) { p.setParameter(key, partam.get(key)); } } if (StringUtils.isNotEmpty(cookies)) { p.addRequestHeader("cookie", cookies); } hc.executeMethod(p); return p.getResponseBodyAsString(); }
Example 19
Source File: UserController.java From OfficeAutomatic-System with Apache License 2.0 | 5 votes |
private void message(String phone,String hysbh,String time) throws IOException { HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://gbk.api.smschinese.cn"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码 NameValuePair[] data = { new NameValuePair("Uid", "dddz97"), new NameValuePair("Key", "d41d8cd98f00b204e980"), new NameValuePair("smsMob", phone), new NameValuePair("smsText", "请于"+time+",到"+hysbh+"开会") }; post.setRequestBody(data); client.executeMethod(post); Header[] headers = post.getResponseHeaders(); int statusCode = post.getStatusCode(); System.out.println("statusCode:" + statusCode); for (Header h : headers) { System.out.println(h.toString()); } String result = new String(post.getResponseBodyAsString().getBytes("gbk")); System.out.println(result); // 打印返回消息状态 post.releaseConnection(); }
Example 20
Source File: AbstractApiCommandProcessor.java From engage-api-client with Apache License 2.0 | 4 votes |
protected PostMethod addRequestHeaders(Map<String, String> headers, PostMethod postMethod) { for (String header : headers.keySet()) { postMethod.addRequestHeader(header, headers.get(header)); } return postMethod; }