public static final String httpClientPost(String url, ArrayList<NameValuePair> list) { String result = ""; HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); try { NameValuePair[] params = new NameValuePair[list.size()]; for (int i = 0; i < list.size(); i++) { params[i] = list.get(i); } postMethod.addParameters(params); client.executeMethod(postMethod); result = postMethod.getResponseBodyAsString(); } catch (Exception e) { logger.error("", e); } finally { postMethod.releaseConnection(); } return result; }
public static final String httpClientPost(String url, ArrayList<NameValuePair> list) { String result = ""; HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); try { NameValuePair[] params = new NameValuePair[list.size()]; for (int i = 0; i < list.size(); i++) { params[i] = list.get(i); } postMethod.addParameters(params); client.executeMethod(postMethod); result = postMethod.getResponseBodyAsString(); } catch (Exception e) { logger.error(e); } finally { postMethod.releaseConnection(); } return result; }
/** * Tests POST via non-authenticating proxy + host auth + connection keep-alive */ public void testPostHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
public void testEnclosedEntityNegativeLengthHTTP1_0() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, -14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(false); method.getParams().setVersion(HttpVersion.HTTP_1_0); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } }
/** * Sends the request to paypal. Input is preapprovalKey of buyer, email of * seller, and amount to be transferred. * * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { final PaypalRequest paypalRequest = new PaypalRequest( request.getRemoteAddr()); final PostMethod post = paypalRequest.buildPayRequest( request.getParameter("preapprovalKey"), request.getParameter("email"), request.getParameter("amount")); setDefaultAttributes(request, paypalRequest, sendPaypalRequest(post)); request.getRequestDispatcher("/payResponse.jsp").forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
/** * Tests POST via authenticating proxy + host auth + connection keep-alive */ public void testPostProxyAuthHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
/** * Help method for log * * @param method method */ protected void toString(HttpMethod method) { logger.info("===============HTTP METHOD==============="); final String path = method.getPath(); logger.info("path = " + path); final Header[] headers = method.getRequestHeaders(); StringBuilder builder = new StringBuilder(); for (Header header : headers) { if (header != null) builder.append(header.toString()); } logger.info("header = \n" + builder.toString().trim()); if (method instanceof PostMethod) { PostMethod postMethod = (PostMethod) method; builder = new StringBuilder(); final NameValuePair[] parameters = postMethod.getParameters(); for (NameValuePair pair : parameters) { builder.append(pair.getName()).append("=").append(pair.getValue()).append("\n"); } } logger.info("post parameters: \n" + builder.toString().trim()); logger.info("query string = " + method.getQueryString()); logger.info("========================================="); }
@Override public HttpResponse post(URL urlObj, byte[] payload, String userName, String password, int timeout) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(urlObj.toString()); method.setRequestEntity(new ByteArrayRequestEntity(payload)); method.setRequestHeader("Content-type", "application/json"); client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); client.getParams().setSoTimeout(1000 * timeout); client.getParams().setConnectionManagerTimeout(1000 * timeout); if (userName != null && password != null) { setBasicAuthorization(method, userName, password); } try { int response = client.executeMethod(method); return new HttpResponse(response, method.getResponseBody()); } catch (IOException e) { throw new RuntimeException("Failed to process post request URL: " + urlObj, e); } finally { method.releaseConnection(); } }
private PostMethod createPostMethod(KalturaParams kparams, KalturaFiles kfiles, String url) { PostMethod method = new PostMethod(url); method.setRequestHeader("Accept","text/xml,application/xml,*/*"); method.setRequestHeader("Accept-Charset","utf-8,ISO-8859-1;q=0.7,*;q=0.5"); if (!kfiles.isEmpty()) { method = this.getPostMultiPartWithFiles(method, kparams, kfiles); } else { method = this.addParams(method, kparams); } if (isAcceptGzipEncoding()) { method.addRequestHeader(HTTP_HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler (3, false)); return method; }
public void testEnclosedEntityChunkedHTTP1_0() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); method.getParams().setVersion(HttpVersion.HTTP_1_0); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); fail("ProtocolException should have been thrown"); } catch (ProtocolException ex) { // expected } finally { method.releaseConnection(); } }
/** * Tests POST via authenticating proxy + host auth + connection close */ public void testPostProxyAuthHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
/** * * Get post method to get csv debug file * * @param jobDetails * @param fileSize * @return {@link PostMethod} * @throws NumberFormatException * @throws MalformedURLException */ public PostMethod getDebugFileMethod(JobDetails jobDetails,String fileSize) throws NumberFormatException, MalformedURLException { URL url = new URL(POST_PROTOCOL, getHost(jobDetails), getPortNo(jobDetails), DebugServiceMethods.GET_DEBUG_FILE_PATH); PostMethod postMethod = new PostMethod(url.toString()); postMethod.addParameter(DebugServicePostParameters.JOB_ID, jobDetails.getUniqueJobID()); postMethod.addParameter(DebugServicePostParameters.COMPONENT_ID, jobDetails.getComponentID()); postMethod.addParameter(DebugServicePostParameters.SOCKET_ID, jobDetails.getComponentSocketID()); postMethod.addParameter(DebugServicePostParameters.BASE_PATH, jobDetails.getBasepath()); postMethod.addParameter(DebugServicePostParameters.USER_ID, jobDetails.getUsername()); postMethod.addParameter(DebugServicePostParameters.DEBUG_SERVICE_PWD, jobDetails.getPassword()); postMethod.addParameter(DebugServicePostParameters.FILE_SIZE, fileSize); postMethod.addParameter(DebugServicePostParameters.HOST_NAME, getHost(jobDetails)); LOGGER.debug("Calling debug service to get csv debug file from url :: "+url); return postMethod; }
public void testEnclosedEntityChunked() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(true); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertNull(method.getRequestHeader("Content-Length")); } finally { method.releaseConnection(); } }
public void chcekConnectionStatus() throws IOException { HttpClient httpClient = new HttpClient(); //TODO : add connection details while testing only,remove it once done String teradatajson = "{\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}"; PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/getConnectionStatus"); //postMethod.addParameter("request_parameters", redshiftjson); postMethod.addParameter("request_parameters", teradatajson); int response = httpClient.executeMethod(postMethod); InputStream inputStream = postMethod.getResponseBodyAsStream(); byte[] buffer = new byte[1024 * 1024 * 5]; String path = null; int length; while ((length = inputStream.read(buffer)) > 0) { path = new String(buffer); } System.out.println("Response of service: " + path); System.out.println("=================="); }
public void calltoReadMetastore() throws IOException { HttpClient httpClient = new HttpClient(); //TODO : add connection details while testing only,remove it once done String teradatajson = "{\"table\":\"testting2\",\"username\":\"\",\"password\":\"\",\"hostname\":\"\",\"database\":\"\",\"dbtype\":\"\",\"port\":\"\"}"; PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/readFromMetastore"); //postMethod.addParameter("request_parameters", redshiftjson); postMethod.addParameter("request_parameters", teradatajson); int response = httpClient.executeMethod(postMethod); InputStream inputStream = postMethod.getResponseBodyAsStream(); byte[] buffer = new byte[1024 * 1024 * 5]; String path = null; int length; while ((length = inputStream.read(buffer)) > 0) { path = new String(buffer); } System.out.println("Response of service: " + path); System.out.println("=================="); }
/** * Tests POST via authenticating proxy */ public void testPostAuthProxy() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setProxyCredentials(AuthScope.ANY, creds); this.server.setHttpService(new FeedbackService()); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
public void calltoReadService() throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod("http://" + HOST_NAME + ":" + PORT + "/read"); postMethod.addParameter("jobId", JOB_ID); postMethod.addParameter("componentId", COMPONENT_ID); postMethod.addParameter("socketId", SOCKET_ID); postMethod.addParameter("basePath", BASE_PATH); postMethod.addParameter("userId", USER_ID); postMethod.addParameter("password", PASSWORD); postMethod.addParameter("file_size", FILE_SIZE_TO_READ); postMethod.addParameter("host_name", HOST_NAME); InputStream inputStream = postMethod.getResponseBodyAsStream(); byte[] buffer = new byte[1024 * 1024 * 5]; String path = null; int length; while ((length = inputStream.read(buffer)) > 0) { path = new String(buffer); } System.out.println("response of service: " + path); }
/** * Tests POST via non-authenticating proxy + invalid host auth */ public void testPostHostInvalidAuth() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testuser", "wrongstuff")); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_UNAUTHORIZED, post.getStatusCode()); } finally { post.releaseConnection(); } }
/** * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive */ public void testPostInteractiveProxyAuthHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); this.proxy.requireAuthentication(creds, "test", true); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
@Test public void processorsActive() throws HttpException, IOException { final PostMethod post = new PostMethod(testUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX); post.setFollowRedirects(false); post.setParameter("DummyModification", "true"); try { T.getHttpClient().executeMethod(post); final String content = post.getResponseBodyAsString(); final int i1 = content.indexOf("source:SlingPostProcessorOne"); assertTrue("Expecting first processor to be present", i1 > 0); final int i2 = content.indexOf("source:SlingPostProcessorTwo"); assertTrue("Expecting second processor to be present", i2 > 0); assertTrue("Expecting service ranking to put processor one first", i1 < i2); } finally { post.releaseConnection(); } }
/** * Tests POST via non-authenticating proxy + interactive host auth + connection keep-alive */ public void testPostInteractiveHostAuthConnKeepAlive() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getParams().setParameter(CredentialsProvider.PROVIDER, new GetItWrongThenGetItRight()); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", true)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
private void simplePost(String url, String statusParam, int expectStatus, String expectLocation) throws IOException { final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); if (statusParam != null) { post.addParameter(SlingPostConstants.RP_STATUS, statusParam); } final int status = httpClient.executeMethod(post); assertEquals("Unexpected status response", expectStatus, status); if (expectLocation != null) { String location = post.getResponseHeader("Location").getValue(); assertNotNull("Expected location header", location); assertTrue(location.endsWith(expectLocation)); } post.releaseConnection(); }
public void testSetRootProperty() throws Exception { String url = HTTP_BASE_URL; if(!url.endsWith("/")) { url += "/"; } final PostMethod post = new PostMethod(url); final String name = getClass().getSimpleName(); final String value = getClass().getSimpleName() + System.currentTimeMillis(); post.addParameter(name, value); final int status = httpClient.executeMethod(post); assertEquals(200, status); final String json = getContent(url + ".json", CONTENT_TYPE_JSON); assertJavascript(value, json, "out.print(data." + name + ")"); }
private void runTest(String acceptHeaderValue, boolean useHttpEquiv, String expectedContentType) throws Exception { final String info = (useHttpEquiv ? "Using http-equiv parameter" : "Using Accept header") + ": "; final String url = HTTP_BASE_URL + MY_TEST_PATH; final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); if(acceptHeaderValue != null) { if(useHttpEquiv) { post.addParameter(":http-equiv-accept", acceptHeaderValue); } else { post.addRequestHeader("Accept", acceptHeaderValue); } } final int status = httpClient.executeMethod(post) / 100; assertEquals(info + "Expected status 20x for POST at " + url, 2, status); final Header h = post.getResponseHeader("Content-Type"); assertNotNull(info + "Expected Content-Type header", h); final String ct = h.getValue(); assertTrue(info + "Expected Content-Type '" + expectedContentType + "' for Accept header=" + acceptHeaderValue + " but got '" + ct + "'", ct.startsWith(expectedContentType)); }
@Test public void testDeleteNonExisting() throws Exception { final String path = TEST_PATH + "/" + EXISTING_PATH; final String testNodeUrl = H.getTestClient().createNode(HttpTest.HTTP_BASE_URL + "/" + path, null); assertTrue("Expecting created node path to end with " + path, testNodeUrl.endsWith(path)); H.assertHttpStatus(testNodeUrl + ".json", 200, "Expecting test node to exist before test"); // POST :delete to non-existing child node with a path that // generates selector + suffix final String selectorsPath = TEST_PATH + "/" + deletePath; final PostMethod post = new PostMethod(HttpTest.HTTP_BASE_URL + "/" + selectorsPath); post.setParameter(":operation", "delete"); final int status = H.getHttpClient().executeMethod(post); assertEquals("Expecting 403 status for delete operation", 403, status); // Test node should still be here H.assertHttpStatus(testNodeUrl + ".json", 200, "Expecting test node to exist after test"); }
/** * Test SLING-2165. Login Error should redirect back to the referrer * login page. * * @throws Exception */ public void testRedirectToLoginFormAfterLoginError() throws Exception { //login failure List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("j_username", "___bogus___")); params.add(new NameValuePair("j_password", "not_a_real_user")); final String loginPageUrl = String.format("%s/system/sling/form/login", HTTP_BASE_URL); PostMethod post = (PostMethod)assertPostStatus(HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY, params, null, loginPageUrl); final Header locationHeader = post.getResponseHeader("Location"); String location = locationHeader.getValue(); int queryStrStart = location.indexOf('?'); if (queryStrStart != -1) { location = location.substring(0, queryStrStart); } assertEquals("Expected to remain on the form/login page", loginPageUrl, location); }
public void testRecentRequestsEscape() throws Exception { final String basePath = "/" + getClass().getSimpleName() + "/" + Math.random(); final String path = basePath + ".html/%22%3e%3cscript%3ealert(29679)%3c/script%3e"; // POST to create node { final PostMethod post = new PostMethod(HTTP_BASE_URL + path); post.setFollowRedirects(false); final int status = httpClient.executeMethod(post); assertEquals(201, status); } // And check that recent requests output does not contain <script> { final String content = getContent(HTTP_BASE_URL + "/system/console/requests?index=1", CONTENT_TYPE_HTML); final String scriptTag = "<script>"; assertFalse("Content should not contain '" + scriptTag + "'", content.contains(scriptTag)); } }
public void testEnclosedEntityAutoLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, InputStreamRequestEntity.CONTENT_LENGTH_AUTO); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNull(method.getRequestHeader("Transfer-Encoding")); assertNotNull(method.getRequestHeader("Content-Length")); assertEquals(input.length, Integer.parseInt( method.getRequestHeader("Content-Length").getValue())); } finally { method.releaseConnection(); } }
public static String getPostResponseHeader(String url,String argJson,List<UHeader> headerList,String headerName){ String info = ""; try { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); client.getParams().setContentCharset("UTF-8"); if(headerList.size()>0){ for(int i = 0;i<headerList.size();i++){ UHeader header = headerList.get(i); method.setRequestHeader(header.getHeaderTitle(),header.getHeaderValue()); } } method.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); if(argJson != null && !argJson.trim().equals("")) { RequestEntity requestEntity = new StringRequestEntity(argJson,"application/json","UTF-8"); method.setRequestEntity(requestEntity); } method.releaseConnection(); Header h = method.getResponseHeader(headerName); info = h.getValue(); } catch (IOException e) { e.printStackTrace(); } return info; }
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId, final String relationCollectionName, final Object relationshipEntityId, final String body, String contentType, final Map<String, String> params) throws IOException { RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); String url = endpoint.getUrl(); PostMethod req = new PostMethod(url.toString()); if (body != null) { if (contentType == null || contentType.isEmpty()) { contentType = "application/json"; } StringRequestEntity requestEntity = new StringRequestEntity(body, contentType, "UTF-8"); req.setRequestEntity(requestEntity); } return submitRequest(req, rq); }
public HttpResponse post(final RequestContext rq, final String scope, final int version, final String entityCollectionName, final Object entityId, final String relationCollectionName, final Object relationshipEntityId, final byte[] body, String contentType) throws IOException { RestApiEndpoint endpoint = new RestApiEndpoint(rq.getNetworkId(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, null); String url = endpoint.getUrl(); PostMethod req = new PostMethod(url.toString()); if (body != null) { if (contentType == null || contentType.isEmpty()) { contentType = "application/octet-stream"; } ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(body, contentType); req.setRequestEntity(requestEntity); } return submitRequest(req, rq); }
/** * Tests POST via non-authenticating proxy + host auth + connection close */ public void testPostHostAuthConnClose() throws Exception { UsernamePasswordCredentials creds = new UsernamePasswordCredentials("testuser", "testpass"); this.client.getState().setCredentials(AuthScope.ANY, creds); HttpRequestHandlerChain handlerchain = new HttpRequestHandlerChain(); handlerchain.appendHandler(new AuthRequestHandler(creds, "test", false)); handlerchain.appendHandler(new HttpServiceHandler(new FeedbackService())); this.server.setRequestHandler(handlerchain); PostMethod post = new PostMethod("/"); post.setRequestEntity(new StringRequestEntity("Like tons of stuff", null, null)); try { this.client.executeMethod(post); assertEquals(HttpStatus.SC_OK, post.getStatusCode()); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
public void testEnclosedEntityNegativeLength() throws Exception { String inputstr = "This is a test message"; byte[] input = inputstr.getBytes("US-ASCII"); InputStream instream = new ByteArrayInputStream(input); RequestEntity requestentity = new InputStreamRequestEntity( instream, -14); PostMethod method = new PostMethod("/"); method.setRequestEntity(requestentity); method.setContentChunked(false); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals(inputstr, body); assertNotNull(method.getRequestHeader("Transfer-Encoding")); assertNull(method.getRequestHeader("Content-Length")); } finally { method.releaseConnection(); } }
/** * Send a POST request * @param cluster the cluster definition * @param path the path or URI * @param headers the HTTP headers to include, <tt>Content-Type</tt> must be * supplied * @param content the content bytes * @return a Response object with response detail * @throws IOException */ public Response post(Cluster cluster, String path, Header[] headers, byte[] content) throws IOException { PostMethod method = new PostMethod(); try { method.setRequestEntity(new ByteArrayRequestEntity(content)); int code = execute(cluster, method, headers, path); headers = method.getResponseHeaders(); content = method.getResponseBody(); return new Response(code, headers, content); } finally { method.releaseConnection(); } }
private static void setPostParams(PostMethod postMethod,Map<String,Object> params){ for (String name : params.keySet()) { postMethod.setParameter(name,String.valueOf(params.get(name))); //parts[i++] = new StringPart(name, String.valueOf(params.get(name)), UTF_8); // System.out.println("post_key==> "+name+" value==>"+String.valueOf(params.get(name))); } }
public String doPost(String url, String charset, String jsonObj) { String resStr = null; HttpClient htpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.getParams().setParameter( HttpMethodParams.HTTP_CONTENT_CHARSET, charset); try { postMethod.setRequestEntity(new StringRequestEntity(jsonObj, "application/json", charset)); int statusCode = htpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { // post和put不能自动处理转发 301:永久重定向,告诉客户端以后应从新地址访问 302:Moved if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = postMethod .getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); log.info("The page was redirected to :" + location); } else { log.info("Location field value is null"); } } else { log.error("Method failed: " + postMethod.getStatusLine()); } return resStr; } byte[] responseBody = postMethod.getResponseBody(); resStr = new String(responseBody, charset); } catch (Exception e) { e.printStackTrace(); } finally { postMethod.releaseConnection(); } return resStr; }