List of usage examples for org.apache.http.client.methods RequestBuilder post
public static RequestBuilder post()
From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java
/** * Login to pulse server and setup httpClient for tests * To be called from setupBeforeClass in each test class *//* ww w . ja v a2s.co m*/ protected static void doLogin() throws Exception { System.out.println("BaseServiceTest :: Executing doLogin with user : admin, password : admin."); CloseableHttpResponse loginResponse = null; try { BasicCookieStore cookieStore = new BasicCookieStore(); httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpUriRequest login = RequestBuilder.post().setUri(new URI(LOGIN_URL)) .addParameter("j_username", "admin").addParameter("j_password", "admin").build(); loginResponse = httpclient.execute(login); try { HttpEntity entity = loginResponse.getEntity(); EntityUtils.consume(entity); System.out.println("BaseServiceTest :: HTTP request status : " + loginResponse.getStatusLine()); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { } else { for (int i = 0; i < cookies.size(); i++) { } } } finally { if (loginResponse != null) loginResponse.close(); } } catch (Exception failed) { logException(failed); throw failed; } System.out.println("BaseServiceTest :: Executed doLogin"); }
From source file:edu.mit.scratch.ScratchProject.java
public boolean comment(final ScratchSession session, final String comment) throws ScratchProjectException { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", session.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", session.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang);// www .j a va 2 s. co m cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)" + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36") .setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final JSONObject obj = new JSONObject(); obj.put("content", comment); obj.put("parent_id", ""); obj.put("commentee_id", ""); final String strData = obj.toString(); HttpUriRequest update = null; try { update = RequestBuilder.post() .setUri("https://scratch.mit.edu/site-api/comments/project/" + this.getProjectID() + "/add/") .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu/projects/" + this.getProjectID() + "/") .addHeader("Origin", "https://scratch.mit.edu/") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("Cookie", "scratchsessionsid=" + session.getSessionID() + "; scratchcsrftoken=" + session.getCSRFToken()) .addHeader("X-CSRFToken", session.getCSRFToken()).setEntity(new StringEntity(strData)).build(); } catch (final UnsupportedEncodingException e1) { e1.printStackTrace(); } try { resp = httpClient.execute(update); System.out.println("cmntadd:" + resp.getStatusLine()); final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); System.out.println("cmtline:" + result.toString()); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } return false; }
From source file:nl.b3p.viewer.admin.ViewerAdminLockoutIntegrationTest.java
/** * Test login/index/about/logout sequentie. * * @throws IOException mag niet optreden * @throws URISyntaxException mag niet optreden *//* w ww . j av a 2 s. c o m*/ @Test public void testBLoginLogout() throws IOException, URISyntaxException { // login page response = client.execute(new HttpGet(BASE_TEST_URL)); EntityUtils.consume(response.getEntity()); HttpUriRequest login = RequestBuilder.post().setUri(new URI(BASE_TEST_URL + "j_security_check")) .addParameter("j_username", "admin").addParameter("j_password", "flamingo").build(); response = client.execute(login); EntityUtils.consume(response.getEntity()); assertThat("Response status is OK.", response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK)); // index response = client.execute(new HttpGet(BASE_TEST_URL + "action/index")); String body = EntityUtils.toString(response.getEntity()); assertNotNull("Response body mag niet null zijn.", body); assertTrue("Response moet 'Beheeromgeving geo-viewers' title hebben.", body.contains("<title>Beheeromgeving geo-viewers</title>")); // about response = client.execute(new HttpGet(BASE_TEST_URL + "about.jsp")); body = EntityUtils.toString(response.getEntity()); assertNotNull("Response body mag niet null zijn.", body); assertTrue("Response moet 'About' title hebben.", body.contains("<title>About</title>")); // logout response = client.execute(new HttpGet(BASE_TEST_URL + "logout.jsp")); body = EntityUtils.toString(response.getEntity()); assertThat("Response status is OK.", response.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_OK)); assertNotNull("Response body mag niet null zijn.", body); assertTrue("Response moet 'Uitgelogd' heading hebben.", body.contains("<h1>Uitgelogd</h1>")); }
From source file:org.dasein.cloud.azure.platform.AzureSQLDatabaseSupportRequests.java
public RequestBuilder createDatabaseFromBackup(String serverName, CreateDatabaseRestoreModel createDatabaseRestoreModel) { RequestBuilder requestBuilder = RequestBuilder.post(); addAzureCommonHeaders(requestBuilder); requestBuilder.setUri(String.format(RESOURCE_RESTORE_DATABASE_OPERATIONS, this.provider.getContext().getAccountNumber(), serverName)); requestBuilder/*from www .j a v a2s .co m*/ .setEntity(new DaseinObjectToXmlEntity<CreateDatabaseRestoreModel>(createDatabaseRestoreModel)); return requestBuilder; }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.ClusterSelectedRegionServiceTest.java
/** * * Tests that response is for same logged in user * *///from ww w. j av a2 s . co m @Test public void testResponseUsername() { System.out.println( "ClusterSelectedRegionServiceTest :: ------TESTCASE BEGIN : NULL USERNAME IN RESPONSE CHECK FOR CLUSTER REGIONS------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_1_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println("ClusterSelectedRegionServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println("ClusterSelectedRegionServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject clusterSelectedRegionObj = jsonObj.getJSONObject("ClusterSelectedRegion"); Assert.assertNotNull( "ClusterSelectedRegionServiceTest :: Server returned null response for ClusterSelectedRegion", clusterSelectedRegionObj); String szUser = clusterSelectedRegionObj.getString("userName"); Assert.assertEquals( "ClusterSelectedRegionServiceTest :: Server returned wrong user name. Expected was admin. Server returned = " + szUser, szUser, "admin"); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("ClusterSelectedRegionServiceTest :: No Http connection was established."); } System.out.println( "ClusterSelectedRegionServiceTest :: ------TESTCASE END : NULL USERNAME IN RESPONSE CHECK FOR CLUSTER REGIONS------\n"); }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.MemberGatewayHubServiceTest.java
/** * * Tests that response is for same region * * Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.MemberGatewayHubService#execute(javax.servlet.http.HttpServletRequest)}. * */// www. j a va2s . co m @Test public void testResponseIsGatewaySender() { System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE BEGIN : IS GATEWAY SENDER IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println( "MemberGatewayHubServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject memberGatewayHubObj = jsonObj.getJSONObject("MemberGatewayHub"); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub", memberGatewayHubObj); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server did not return 'isGatewaySender' for member", memberGatewayHubObj.has("isGatewaySender")); Boolean boolIsGatewaySender = memberGatewayHubObj.getBoolean("isGatewaySender"); Assert.assertEquals( "MemberGatewayHubServiceTest :: Server returned wrong value for 'isGatewaySender'. Expected 'isGatewaySender' = true, actual 'isGatewaySender' = " + boolIsGatewaySender, boolIsGatewaySender, true); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established."); } System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE END : IS GATEWAY SENDER IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n"); }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.ClusterSelectedRegionsMemberServiceTest.java
/** * * Tests that response is for same logged in user * *///from w w w.ja v a 2s . com @Test public void testResponseUsername() { System.out.println( "ClusterSelectedRegionsMemberServiceTest :: ------TESTCASE BEGIN : NULL USERNAME IN RESPONSE CHECK FOR CLUSTER REGION MEMBERS------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_3_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println("ClusterSelectedRegionsMemberServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println( "ClusterSelectedRegionsMemberServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject clusterSelectedRegionObj = jsonObj.getJSONObject("ClusterSelectedRegionsMember"); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null response for ClusterSelectedRegionsMember", clusterSelectedRegionObj); Assert.assertTrue( "ClusterSelectedRegionsMemberServiceTest :: Server did not return 'userName' in request", clusterSelectedRegionObj.has("userName")); String szUser = clusterSelectedRegionObj.getString("userName"); Assert.assertEquals( "ClusterSelectedRegionsMemberServiceTest :: Server returned wrong user name. Expected was admin. Server returned = " + szUser, szUser, "admin"); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("ClusterSelectedRegionsMemberServiceTest :: No Http connection was established."); } System.out.println( "ClusterSelectedRegionsMemberServiceTest :: ------TESTCASE END : NULL USERNAME IN RESPONSE CHECK FOR CLUSTER REGION MEMBERS------"); }
From source file:net.liuxuan.Tools.signup.SignupQjvpn.java
public void doLoginAction() throws IOException, URISyntaxException { RequestBuilder builder = RequestBuilder.post().setUri(new URI("http://www.qjvpn.com/user/checklogin.php")) .addParameter("username", "lx0319").addParameter("password", "mosesmoses"); for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) { NameValuePair nameValuePair = it.next(); builder.addParameter(nameValuePair); }// www.j a v a 2s. co m HttpUriRequest login = builder.build(); // HttpUriRequest login = RequestBuilder.post() // .setUri(new URI("http://v2ex.com/signin")) // .addParameter("u", "mosliu") // .addParameter("p", "mosesmoses") // .build(); CloseableHttpResponse response = httpclient.execute(login); // HttpPost httppost = new HttpPost("http://v2ex.com/signin"); // UrlEncodedFormEntity uefEntity;//?? // setUserAndPass(); // uefEntity = new UrlEncodedFormEntity(params, "utf-8"); // httppost.setEntity(uefEntity); // CloseableHttpResponse response; // // response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response.close(); } }
From source file:nya.miku.wishmaster.http.streamer.HttpStreamer.java
/** * HTTP ? ?. ? ? ? ?, release() !/*from w w w . j av a 2 s. com*/ * ? ? ?? ? ? If-Modified-Since, ? * ? ?? ? Modified ({@link #removeFromModifiedMap(String)})! * @param url ? ? * @param requestModel ? ( null, GET If-Modified) * @param httpClient HTTP , ?? ? * @param listener ? ?? ?? ( null) * @param task , ( null) * @return ? HTTP * @throws HttpRequestException ?, ? ? ? */ public HttpResponseModel getFromUrl(String url, HttpRequestModel requestModel, HttpClient httpClient, ProgressListener listener, CancellableTask task) throws HttpRequestException { if (requestModel == null) requestModel = HttpRequestModel.builder().setGET().build(); // Request HttpUriRequest request = null; try { RequestConfig requestConfigBuilder = ExtendedHttpClient .getDefaultRequestConfigBuilder(requestModel.timeoutValue) .setRedirectsEnabled(!requestModel.noRedirect).build(); RequestBuilder requestBuilder = null; switch (requestModel.method) { case HttpRequestModel.METHOD_GET: requestBuilder = RequestBuilder.get().setUri(url); break; case HttpRequestModel.METHOD_POST: requestBuilder = RequestBuilder.post().setUri(url).setEntity(requestModel.postEntity); break; default: throw new IllegalArgumentException("Incorrect type of HTTP Request"); } if (requestModel.customHeaders != null) { for (Header header : requestModel.customHeaders) { requestBuilder.addHeader(header); } } if (requestModel.checkIfModified && requestModel.method == HttpRequestModel.METHOD_GET) { synchronized (ifModifiedMap) { if (ifModifiedMap.containsKey(url)) { requestBuilder .addHeader(new BasicHeader(HttpHeaders.IF_MODIFIED_SINCE, ifModifiedMap.get(url))); } } } request = requestBuilder.setConfig(requestConfigBuilder).build(); } catch (Exception e) { Logger.e(TAG, e); HttpResponseModel.release(request, null); throw new IllegalArgumentException(e); } // ? HttpResponseModel responseModel = new HttpResponseModel(); HttpResponse response = null; try { IOException responseException = null; for (int i = 0; i < 5; ++i) { try { if (task != null && task.isCancelled()) throw new InterruptedException(); response = httpClient.execute(request); responseException = null; break; } catch (IOException e) { Logger.e(TAG, e); responseException = e; if (e.getMessage() == null) break; if (e.getMessage().indexOf("Connection reset by peer") != -1 || e.getMessage().indexOf("I/O error during system call, Broken pipe") != -1) { continue; } else { break; } } } if (responseException != null) { throw responseException; } if (task != null && task.isCancelled()) throw new InterruptedException(); // ???? HTTP StatusLine status = response.getStatusLine(); responseModel.statusCode = status.getStatusCode(); responseModel.statusReason = status.getReasonPhrase(); // (headers) String lastModifiedValue = null; if (responseModel.statusCode == 200) { Header header = response.getFirstHeader(HttpHeaders.LAST_MODIFIED); if (header != null) lastModifiedValue = header.getValue(); } Header header = response.getFirstHeader(HttpHeaders.LOCATION); if (header != null) responseModel.locationHeader = header.getValue(); responseModel.headers = response.getAllHeaders(); // HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { responseModel.contentLength = responseEntity.getContentLength(); if (listener != null) listener.setMaxValue(responseModel.contentLength); InputStream stream = responseEntity.getContent(); responseModel.stream = IOUtils.modifyInputStream(stream, listener, task); } responseModel.request = request; responseModel.response = response; if (lastModifiedValue != null) { synchronized (ifModifiedMap) { ifModifiedMap.put(url, lastModifiedValue); } } } catch (Exception e) { Logger.e(TAG, e); HttpResponseModel.release(request, response); throw new HttpRequestException(e); } return responseModel; }
From source file:net.liuxuan.Tools.signup.SignupV2ex.java
public void doLoginAction() throws IOException, URISyntaxException { RequestBuilder builder = RequestBuilder.post().setUri(new URI("http://v2ex.com/signin")) .addParameter("u", "mosliu").addParameter("p", "mosesmoses"); for (Iterator<NameValuePair> it = params.iterator(); it.hasNext();) { NameValuePair nameValuePair = it.next(); builder.addParameter(nameValuePair); }// w ww. j a va 2s. c o m HttpUriRequest login = builder.build(); // HttpUriRequest login = RequestBuilder.post() // .setUri(new URI("http://v2ex.com/signin")) // .addParameter("u", "mosliu") // .addParameter("p", "mosesmoses") // .build(); CloseableHttpResponse response = httpclient.execute(login); // HttpPost httppost = new HttpPost("http://v2ex.com/signin"); // UrlEncodedFormEntity uefEntity;//?? // setUserAndPass(); // uefEntity = new UrlEncodedFormEntity(params, "utf-8"); // httppost.setEntity(uefEntity); // CloseableHttpResponse response; // // response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { response.close(); } }