/** * Factory method to create a {@link HttpMethod}-object according to the * given String <code>httpMethod</codde> * * @param httpMethodString the name of the {@link HttpMethod} to create * @param url * * @return an object of type {@link GetMethod}, {@link PutMethod}, * {@link PostMethod} or {@link DeleteMethod} * @throws IllegalArgumentException if <code>httpMethod</code> is none of * <code>GET</code>, <code>PUT</code>, <code>POST</POST> or <code>DELETE</code> */ public static HttpMethod createHttpMethod(String httpMethodString, String url) { if ("GET".equals(httpMethodString)) { return new GetMethod(url); } else if ("PUT".equals(httpMethodString)) { return new PutMethod(url); } else if ("POST".equals(httpMethodString)) { return new PostMethod(url); } else if ("DELETE".equals(httpMethodString)) { return new DeleteMethod(url); } else { throw new IllegalArgumentException("given httpMethod '" + httpMethodString + "' is unknown"); } }
public static PostMethod sendMultipartPostRequest(String url, String body) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); // our handlers ignore key...so we can put anything here Part[] parts = {new StringPart("body", body)}; postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams())); httpClient.executeMethod(postMethod); return postMethod; }
/** * Uses the post method to send a url with arguments by http, this method can call RESTful Api. * * @param url the http url * @param timeout milliseconds to wait for the server to respond before giving up * @param processInputStream the response body stream processor */ public static void post(String url, Integer timeout, IProcessInputStream processInputStream) throws IOException { Preconditions.checkNotNull(timeout, "timeout"); Preconditions.checkNotNull(processInputStream, "processInputStream"); PostMethod postMethod = new PostMethod(url); try { HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout); httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout); int statusCode = httpClient.executeMethod(postMethod); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { InputStream inputStream = postMethod.getResponseBodyAsStream(); processInputStream.process(inputStream); } else { throw new IOException("Failed to perform POST request. Status code: " + statusCode); } } finally { postMethod.releaseConnection(); } }
PostMethod post = new PostMethod("http://jakarata.apache.org/"); NameValuePair[] data = { new NameValuePair("user", "joe"), new NameValuePair("password", "bloggs") }; post.setRequestBody(data); // execute method and handle any error responses. ... InputStream in = post.getResponseBodyAsStream(); // handle response.
StringRequestEntity requestEntity = new StringRequestEntity( JSON_STRING, "application/json", "UTF-8"); PostMethod postMethod = new PostMethod("http://example.com/action"); postMethod.setRequestEntity(requestEntity); int statusCode = httpClient.executeMethod(postMethod);
/** * Sets the value of parameter with parameterName to parameterValue. This method * does not preserve the initial insertion order. * * @param parameterName name of the parameter * @param parameterValue value of the parameter * * @since 2.0 */ public void setParameter(String parameterName, String parameterValue) { LOG.trace("enter PostMethod.setParameter(String, String)"); removeParameter(parameterName); addParameter(parameterName, parameterValue); }
@Override public void connect() throws ConnectionException { PostMethod post = new PostMethod(conn.getConnectUrl()); HttpClient httpClient = new HttpClient(); if (conn.getConnectUrl().toLowerCase().startsWith("https://")) { registerSsl(); } addPostHeaders(post); try { StringRequestEntity requestEntity = new StringRequestEntity("{}", "application/json", "UTF-8"); post.setRequestEntity(requestEntity); httpClient.executeMethod(post); if (post.getStatusCode() != 200 && post.getStatusCode() != 201) { logger.error("Connect failed with error code " + post.getStatusCode() + " and message:\n" + post.getResponseBodyAsString()); throw new ConnectionException("Connect failed, error code " + post.getStatusCode() + " and message: " + post.getResponseBodyAsString()); } } catch (HttpException e) { logger.error(e.getLocalizedMessage(), e); throw new ConnectionException(e.getLocalizedMessage()); } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); throw new ConnectionException(e.getLocalizedMessage()); } }
public UserDetails getUserAttributes(String token) throws IOException, SingleSignOnException { HttpClient httpClient = new HttpClient(); PostMethod post = new PostMethod(IDENT_ATTR_ENDPOINT); LOG.log(Level.INFO, "Obtaining user attributes: token: [" + token + "]: REST url: [" + IDENT_ATTR_ENDPOINT + "]"); NameValuePair[] data = { new NameValuePair("subjectid", token) }; post.setRequestBody(data); httpClient.executeMethod(post); if (post.getStatusCode() != HttpStatus.SC_OK) { throw new SingleSignOnException(post.getStatusLine().toString()); } return parseUserDetails(post.getResponseBodyAsString().trim()); }
HttpClient client = new HttpClient(); PostMethod post = new PostMethod("http://jakarata.apache.org/"); NameValuePair[] data = { new NameValuePair("user", "joe"), new NameValuePair("password", "bloggs") }; post.setRequestBody(data); int returnCode = client.execute(post); // check return code ... InputStream in = post.getResponseBodyAsStream();
@Override public HTTPResponse post( final URL url, final InputStream postContent, final String postContentType) throws IOException { PostMethod postMethod = new PostMethod(url.toExternalForm()); postMethod.setDoAuthentication(user != null && password != null); if (postContentType != null) { postMethod.setRequestHeader("Content-type", postContentType); } RequestEntity requestEntity = new InputStreamRequestEntity(postContent); postMethod.setRequestEntity(requestEntity); int responseCode = client.executeMethod(postMethod); if (200 != responseCode) { postMethod.releaseConnection(); throw new IOException( "Server returned HTTP error code " + responseCode + " for URL " + url.toExternalForm()); } return new HttpMethodResponse(postMethod); }
PostMethod post = new PostMethod(url); post.addParameter("schema", schema.toString()); LOG.debug("Loading: " + post.getURI()); int statusCode = httpClient.executeMethod(post); if (statusCode != HttpStatus.SC_CREATED) { throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode); response = post.getResponseBodyAsString(); if (response != null) { LOG.info("Received response " + response); Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME); if (headers.length != 1) { throw new SchemaRegistryException( throw new SchemaRegistryException(t); } finally { post.releaseConnection(); this.httpClientPool.returnObject(httpClient);
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; post.releaseConnection();
public String call(String xml) { PostMethod post = new PostMethod(url); post.setRequestEntity(new StringRequestEntity(xml)); post.setRequestHeader("Content-type", "text/xml"); int result = client.executeMethod(post); if (result == 302) { Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { redirectLocation = locationHeader.getValue(); throw new CloudRuntimeException("Call failed: Bad redirect from UCS Manager"); post.setURI(new URI(redirectLocation)); result = client.executeMethod(post); throw new CloudRuntimeException("Call failed: " + post.getResponseBodyAsString()); String res = post.getResponseBodyAsString(); if (res.contains("errorCode")) { String err = String.format("ucs call failed:\nsubmitted doc:%s\nresponse:%s\n", xml, res); throw new CloudRuntimeException(e.getMessage(), e); } finally { post.releaseConnection();
public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) { PostMethod post = new PostMethod(String.format( "http://%s:%s", agentIp, getPort())); try { 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); } finally { if (post != null) { post.releaseConnection();
PostMethod httpPost = new PostMethod(url.toString()); try { Part[] parts = {new StringPart(schema.getSchemaName(), schema.toString())}; MultipartRequestEntity requestEntity = new MultipartRequestEntity(parts, new HttpMethodParams()); httpPost.setRequestEntity(requestEntity); int responseCode = HTTP_CLIENT.executeMethod(httpPost); if (responseCode >= 400) { String response = httpPost.getResponseBodyAsString(); LOGGER.warn("Got error response code: {}, response: {}", responseCode, response); return false; httpPost.releaseConnection();
break; case GET: http = (request.body() == null ? new GetMethod() : new GetMethodWithBody()); break; case POST: http = new PostMethod(); break; case PUT: http = new PutMethod(); break; client.executeMethod(http); } finally { stats.netTotalTime += (System.currentTimeMillis() - start);
httpMethod = new GetMethod(urlString); } else if ((method.equalsIgnoreCase("POST"))) { httpMethod = new PostMethod(urlString); } else if ((method.equalsIgnoreCase("PUT"))) { httpMethod = new PutMethod(urlString); } else if ((method.equalsIgnoreCase("DELETE"))) { httpMethod = new DeleteMethod(urlString); StringRequestEntity requestEntity = new StringRequestEntity(jsonContent, "application/json", "UTF-8"); ((EntityEnclosingMethod)httpMethod).setRequestEntity(requestEntity); trace("Payload: " + jsonContent);
File file = new File("FileToSend.txt"); HttpClient client = new HttpClient(); String url = "http://www.yourdomain.com/destination.php"; PostMethod postMethod = new PostMethod(url); Part[] parts = {new FilePart(file.getName(), file)}; postMethod.setParameter("name", "value"); // set parameters like this instead in separate call postMethod.setRequestEntity( new MultipartRequestEntity(parts, postMethod.getParams())); int status = client.executeMethod(postMethod);
public Response execute(Command command) throws Exception { CommandInfo info = nameToUrl.get(command.getMethodName()); HttpMethod httpMethod = info.getMethod(remotePath, command); httpMethod.addRequestHeader("Accept", "application/json, image/png"); String payload = new BeanToJsonConverter().convert(command.getParameters()); if (httpMethod instanceof PostMethod) { ((PostMethod) httpMethod) .setRequestEntity(new StringRequestEntity(payload, "application/json", "UTF-8")); } client.executeMethod(httpMethod); // TODO: SimonStewart: 2008-04-25: This is really shabby if (isRedirect(httpMethod)) { Header newLocation = httpMethod.getResponseHeader("location"); httpMethod = new GetMethod(newLocation.getValue()); httpMethod.setFollowRedirects(true); httpMethod.addRequestHeader("Accept", "application/json, image/png"); client.executeMethod(httpMethod); } return createResponse(httpMethod); }
(...) String url = "http://<XXXX>.appspot.com/api/1/Employee/list/p1/50"; HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); client.executeMethod(get); System.out.println(new String(get.getResponseBody())); get.releaseConnection(); url = "http://<XXXX>.appspot.com/api/1/Employee/submit"; PostMethod post = new PostMethod(url); post.addParameter("id", "10"); client.executeMethod(post); System.out.println(new String(post.getResponseBody())); post.releaseConnection(); (...)