List of usage examples for org.apache.http.client.methods HttpPost getEntity
public HttpEntity getEntity()
From source file:com.socialize.test.unit.SocializeRequestFactoryTest.java
@UsesMocks({ UserProviderCredentialsMap.class, AuthProviderData.class, AuthProviderInfo.class, UserProviderCredentials.class }) public void testAuthRequestCreate() throws Exception { SocializeSession session = AndroidMock.createMock(SocializeSession.class); UserProviderCredentialsMap userProviderCredentialsMap = AndroidMock .createMock(UserProviderCredentialsMap.class); AuthProviderData data = AndroidMock.createMock(AuthProviderData.class); AuthProviderInfo authProviderInfo = AndroidMock.createMock(AuthProviderInfo.class); UserProviderCredentials userProviderCredentials = AndroidMock.createMock(UserProviderCredentials.class); AuthProviderType type = AuthProviderType.SOCIALIZE; final String endpoint = "foobar/"; final String udid = "testid"; final String accessToken = "foobar_accessToken"; final String tokenSecret = "foobar_tokenSecret"; final String userId = "foobar_userId"; OAuthRequestSigner signer = new OAuthRequestSigner() { @Override//ww w. j a va 2s. co m public <R extends HttpUriRequest> R sign(SocializeSession session, R request, OAuthSignListener listener) throws SocializeException { assertTrue(request instanceof HttpPost); HttpPost post = (HttpPost) request; assertEquals(post.getURI().toString(), endpoint); assertNotNull(post.getEntity()); addResult(true); return request; } @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request) throws SocializeException { return sign(session, request, null); } @Override public <R extends HttpUriRequest> R sign(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, R request, OAuthSignListener listener) throws SocializeException { return null; } }; SocializeRequestFactory<SocializeObject> factory = new DefaultSocializeRequestFactory<SocializeObject>( signer, null); AndroidMock.expect(session.getUserProviderCredentials()).andReturn(userProviderCredentialsMap); AndroidMock.expect(data.getAuthProviderInfo()).andReturn(authProviderInfo); AndroidMock.expect(authProviderInfo.getType()).andReturn(type).anyTimes(); AndroidMock.expect(userProviderCredentialsMap.get(type)).andReturn(userProviderCredentials); AndroidMock.expect(userProviderCredentials.getAuthProviderInfo()).andReturn(authProviderInfo).anyTimes(); AndroidMock.expect(userProviderCredentials.getAccessToken()).andReturn(accessToken).anyTimes(); AndroidMock.expect(userProviderCredentials.getTokenSecret()).andReturn(tokenSecret).anyTimes(); AndroidMock.expect(userProviderCredentials.getUserId()).andReturn(userId).anyTimes(); AndroidMock.replay(session, data, authProviderInfo, userProviderCredentialsMap, userProviderCredentials); HttpUriRequest req = factory.getAuthRequest(session, endpoint, udid, data); assertTrue(req instanceof HttpPost); HttpPost post = (HttpPost) req; HttpEntity entity = post.getEntity(); assertNotNull(entity); assertTrue(entity instanceof UrlEncodedFormEntity); List<NameValuePair> parsed = URLEncodedUtils.parse(entity); assertEquals(1, parsed.size()); NameValuePair nvp = parsed.get(0); assertEquals("payload", nvp.getName()); JSONObject jsonExpected = new JSONObject(); jsonExpected.put("udid", udid); jsonExpected.put("auth_type", type.getId()); jsonExpected.put("auth_token", accessToken); jsonExpected.put("auth_token_secret", tokenSecret); jsonExpected.put("auth_id", userId); assertEquals(jsonExpected.toString(), nvp.getValue()); assertTrue((Boolean) getNextResult()); AndroidMock.verify(session); }
From source file:autopostsoicomputer.API.WPApi.java
@Override public String generateImage(String strUrlWordpress, String imageUrl) { strUrlWordpress += "generateImage.php"; try {//from ww w .j a v a2 s. co m HttpClient client = new DefaultHttpClient(); ////// HttpPost post = new HttpPost(strUrlWordpress); // add header post.setHeader("User-Agent", "PosterBotDefault"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("user", USER)); urlParameters.add(new BasicNameValuePair("pass", PASS)); urlParameters.add(new BasicNameValuePair("image_future", imageUrl)); post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); HttpResponse response = client.execute(post); System.out.println("\nSending 'POST' request to URL : " + strUrlWordpress); System.out.println("Post parameters : " + post.getEntity()); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString(); } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:com.comcast.drivethru.client.ClientExecuteTest.java
@Test(dataProvider = "exceptionTests") public void testExecuteExceptions(Throwable thrown, Class<?> expected, String messagePart) throws Exception { RestRequest request = new RestRequest(new URL().setPath("/").addQuery("q", "stuff"), POST); request.setContentType("application/json"); request.setBody("{ \"name\" : \"Clark\" }"); request.addHeader("x-transaction-id", "0011223344556677"); Capture<HttpPost> capture = EasyMock.newCapture(); Capture<HttpPost> capture2 = EasyMock.newCapture(); HttpClient delegate = createMock(HttpClient.class); expect(delegate.execute(capture(capture))).andThrow(thrown); SecurityProvider securityProvider = createMock(SecurityProvider.class); securityProvider.sign(capture(capture2)); expectLastCall();//from w w w .ja va 2 s .co m replay(delegate, securityProvider); String base = "http://www.google.com"; DefaultRestClient client = new DefaultRestClient(base, delegate); client.addDefaultHeader("Fintan", "The Salmon of Knowledge"); client.setSecurityProvider(securityProvider); Throwable actual = null; try { client.execute(request); } catch (Throwable t) { actual = t; } finally { client.close(); } /* Verify the thrown exception */ assertNotNull(actual); assertEquals(actual.getClass(), expected); assertTrue(actual.getMessage().contains(messagePart)); /* Verify the constructed request object */ assertTrue(capture.hasCaptured()); HttpPost req = capture.getValue(); assertEquals(req.getLastHeader("Content-Type").getValue(), "application/json"); assertEquals(req.getLastHeader("x-transaction-id").getValue(), "0011223344556677"); assertEquals(req.getLastHeader("Fintan").getValue(), "The Salmon of Knowledge"); assertEquals(req.getURI().toString(), "http://www.google.com/?q=stuff"); /* Verify the "aborted" status of the request */ assertEquals(req.isAborted(), true); /* Read and verify the contents of the request */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(req.getEntity().getContent(), baos); assertEquals(baos.toString(), "{ \"name\" : \"Clark\" }"); /* Verify Security was called with same element */ assertTrue(capture2.hasCaptured()); assertSame(capture2.getValue(), req); verify(delegate, securityProvider); }
From source file:com.comcast.drivethru.client.ClientExecuteTest.java
@Test public void testExecuteSuccess() throws Exception { String body = "this is a response from the internet"; HttpEntity entity = new ByteArrayEntity(body.getBytes()); BasicHttpResponse resp = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 200, "OK"); resp.setHeader("a", "apple"); resp.setHeader("b", "bobcat"); resp.setHeader("Content-Type", "text/plain"); resp.setEntity(entity);//from ww w . j av a 2s. co m RestRequest request = new RestRequest(new URL().setPath("/").addQuery("q", "stuff"), POST); request.setContentType("application/json"); request.setBody("{ \"name\" : \"Clark\" }"); request.addHeader("x-transaction-id", "0011223344556677"); Capture<HttpPost> capture = EasyMock.newCapture(); Capture<HttpPost> capture2 = EasyMock.newCapture(); HttpClient delegate = createMock(HttpClient.class); expect(delegate.execute(capture(capture))).andReturn(resp); SecurityProvider securityProvider = createMock(SecurityProvider.class); securityProvider.sign(capture(capture2)); expectLastCall(); replay(delegate, securityProvider); String base = "http://www.google.com"; DefaultRestClient client = new DefaultRestClient(base, delegate); client.addDefaultHeader("Fintan", "The Salmon of Knowledge"); client.setSecurityProvider(securityProvider); RestResponse response = client.execute(request); client.close(); assertEquals(response.getBodyString(), body); assertEquals(response.getStatusCode(), 200); assertEquals(response.getStatusMessage(), "OK"); assertEquals(response.getContentType(), "text/plain"); assertEquals(response.getHeaderValue("a"), "apple"); assertEquals(response.getHeaderValue("b"), "bobcat"); /* Verify the constructed request object */ assertTrue(capture.hasCaptured()); HttpPost req = capture.getValue(); assertEquals(req.getLastHeader("Content-Type").getValue(), "application/json"); assertEquals(req.getLastHeader("x-transaction-id").getValue(), "0011223344556677"); assertEquals(req.getLastHeader("Fintan").getValue(), "The Salmon of Knowledge"); assertEquals(req.getURI().toString(), "http://www.google.com/?q=stuff"); /* Verify the "aborted" status of the request */ assertEquals(req.isAborted(), true); /* Read and verify the contents of the request */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(req.getEntity().getContent(), baos); assertEquals(baos.toString(), "{ \"name\" : \"Clark\" }"); /* Verify Security was called with same element */ assertTrue(capture2.hasCaptured()); assertSame(capture2.getValue(), req); verify(delegate, securityProvider); }
From source file:autopostsoicomputer.API.WPApi.java
@Override public String getCategoryId(String strUrlWordpress, String slug) { strUrlWordpress += "getCategory.php"; try {/*from w ww . ja v a 2 s. com*/ HttpClient client = new DefaultHttpClient(); ////// HttpPost post = new HttpPost(strUrlWordpress); // add header post.setHeader("User-Agent", "PosterBotDefault"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("user", USER)); urlParameters.add(new BasicNameValuePair("pass", PASS)); /// urlParameters.add(new BasicNameValuePair("slug", slug)); post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); HttpResponse response = client.execute(post); System.out.println("\nSending 'POST' request to URL : " + strUrlWordpress); System.out.println("Post parameters : " + post.getEntity()); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } return result.toString().replaceAll("adminSoiComputer123asdzxc!@#ASDZXC", ""); } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:com.vsct.dt.hesperides.feedback.FeedbacksAggregate.java
@Override public void sendFeedbackToHipchat(final User user, final FeedbackJson template) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Feedback from " + user.getUsername() + " to hipchat room\n" + template.toJsonString()); }//from www.j av a 2 s. c o m final String imageData = template.getFeedback().getImg().split(",")[1]; final String imageName = String.format("feedback_%s.png", template.getFeedback().getTimestamp()); try { final String applicationPath; final Iterator<Map.Entry<String, String>> itOverride = assetsConfiguration.getOverrides().iterator(); if (itOverride.hasNext()) { applicationPath = itOverride.next().getValue(); } else { throw new HesperidesException("Could not create Feedback: asserts configuration not valid"); } LOGGER.debug("Server path : {}", applicationPath); writeImage(getServerPathImageName(applicationPath, imageName), imageData); CloseableHttpClient httpClient = getHttpClient(); HttpPost postRequest = new HttpPost(getHipchatUrl()); StringEntity input = new StringEntity(getHipchatMessageBody(template, imageName, user)); input.setContentType("application/json"); postRequest.setEntity(input); // LOG if (LOGGER.isDebugEnabled()) { LOGGER.debug("------------- Post send Hipchat request ------------------------------------------"); LOGGER.debug(postRequest.toString()); LOGGER.debug("------------- Post send Hipchat content request ---------------------------------"); LOGGER.debug(getStringContent(postRequest.getEntity())); } HttpResponse postResponse = httpClient.execute(postRequest); // LOG LOGGER.debug("------------- Post send Hipchat response ------------------------------------------"); LOGGER.debug(postResponse.toString()); if (postResponse.getStatusLine().getStatusCode() != 204) { throw new RuntimeException( "Failed : HTTP error code : " + postResponse.getStatusLine().getStatusCode()); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.intel.iotkitlib.LibHttp.HttpPostTask.java
private CloudResponse doWork(HttpClient httpClient, String url) { try {/*from w w w.j av a 2s. c o m*/ HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); if (httpBody != null) { //setting HTTP body in entity StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8"); httpPost.setEntity(bodyEntity); } //adding headers one by one for (NameValuePair nvp : headerList) { httpPost.addHeader(nvp.getName(), nvp.getValue()); } if (debug) { Log.e(TAG, "URI is : " + httpPost.getURI()); Header[] headers = httpPost.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue()); } if (httpBody != null) { BufferedReader reader123 = new BufferedReader( new InputStreamReader(httpPost.getEntity().getContent(), HTTP.UTF_8)); StringBuilder builder123 = new StringBuilder(); for (String line = null; (line = reader123.readLine()) != null;) { builder123.append(line).append("\n"); } Log.e(TAG, "Body is :" + builder123.toString()); } } HttpResponse response = httpClient.execute(httpPost, localContext); if (response != null && response.getStatusLine() != null) { if (debug) Log.d(TAG, "response: " + response.getStatusLine().getStatusCode()); } HttpEntity responseEntity = response != null ? response.getEntity() : null; StringBuilder builder = new StringBuilder(); if (responseEntity != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8)); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } if (debug) Log.d(TAG, "Response received is :" + builder.toString()); } CloudResponse cloudResponse = new CloudResponse(); if (response != null) { cloudResponse.code = response.getStatusLine().getStatusCode(); } cloudResponse.response = builder.toString(); return cloudResponse; } catch (java.net.ConnectException cEx) { Log.e(TAG, cEx.getMessage()); return null; } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); return null; } }
From source file:com.intel.iotkitlib.http.HttpPostTask.java
public CloudResponse doSync(final String url) { HttpClient httpClient = new DefaultHttpClient(); try {/* w ww . j a va 2 s . c o m*/ HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); if (httpBody != null) { //setting HTTP body in entity StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8"); httpPost.setEntity(bodyEntity); } //adding headers one by one for (NameValuePair nvp : headerList) { httpPost.addHeader(nvp.getName(), nvp.getValue()); } if (debug) { Log.e(TAG, "URI is : " + httpPost.getURI()); Header[] headers = httpPost.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue()); } if (httpBody != null) { BufferedReader reader123 = new BufferedReader( new InputStreamReader(httpPost.getEntity().getContent(), HTTP.UTF_8)); StringBuilder builder123 = new StringBuilder(); for (String line = null; (line = reader123.readLine()) != null;) { builder123.append(line).append("\n"); } Log.e(TAG, "Body is :" + builder123.toString()); } } HttpResponse response = httpClient.execute(httpPost, localContext); if (response != null && response.getStatusLine() != null) { if (debug) Log.d(TAG, "response: " + response.getStatusLine().getStatusCode()); } HttpEntity responseEntity = response != null ? response.getEntity() : null; StringBuilder builder = new StringBuilder(); if (responseEntity != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8)); for (String line = null; (line = reader.readLine()) != null;) { builder.append(line).append("\n"); } if (debug) Log.d(TAG, "Response received is :" + builder.toString()); } CloudResponse cloudResponse = new CloudResponse(); if (response != null) { cloudResponse.code = response.getStatusLine().getStatusCode(); } cloudResponse.response = builder.toString(); return cloudResponse; } catch (java.net.ConnectException cEx) { Log.e(TAG, cEx.getMessage()); return new CloudResponse(false, cEx.getMessage()); } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); return new CloudResponse(false, e.getMessage()); } }