List of usage examples for org.apache.http.client.entity UrlEncodedFormEntity getContent
public InputStream getContent() throws IOException
From source file:com.glaf.core.util.http.HttpClientUtils.java
/** * ??POST//from www. j av a 2 s.c om * * @param url * ?? * @param encoding * * @param dataMap * ? * * @return */ public static String doPost(String url, String encoding, Map<String, String> dataMap) { StringBuffer buffer = new StringBuffer(); HttpPost post = null; InputStreamReader is = null; BufferedReader reader = null; BasicCookieStore cookieStore = new BasicCookieStore(); HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.setDefaultCookieStore(cookieStore).build(); try { post = new HttpPost(url); if (dataMap != null && !dataMap.isEmpty()) { List<org.apache.http.NameValuePair> nameValues = new ArrayList<org.apache.http.NameValuePair>(); for (Map.Entry<String, String> entry : dataMap.entrySet()) { String name = entry.getKey().toString(); String value = entry.getValue(); nameValues.add(new BasicNameValuePair(name, value)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValues, encoding); post.setEntity(entity); } HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); is = new InputStreamReader(entity.getContent(), encoding); reader = new BufferedReader(is); String tmp = reader.readLine(); while (tmp != null) { buffer.append(tmp); tmp = reader.readLine(); } } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } finally { IOUtils.closeStream(reader); IOUtils.closeStream(is); if (post != null) { post.releaseConnection(); } try { client.close(); } catch (IOException ex) { } } return buffer.toString(); }
From source file:tagtime.beeminder.BeeminderAPI.java
/** * Runs a post request.//from w w w. j ava 2s. com * @return The response if the request completed successfully, or * null otherwise. If this is null, then Beeminder is * probably inaccessible, and no more requests should be sent * for now. Otherwise, make sure to run EntityUtils.consume() * on it. */ private static HttpResponse runPostRequest(HttpClient client, TagTime tagTimeInstance, String dataURL, List<NameValuePair> postData) { //add the authorization token postData.add(new BasicNameValuePair("auth_token", tagTimeInstance.settings.getStringValue(SettingType.AUTH_TOKEN))); //build the request HttpPost postRequest = new HttpPost(dataURL); HttpResponse response; try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData); System.out.println("POST " + dataURL + "?" + new BufferedReader(new InputStreamReader(entity.getContent())).readLine()); postRequest.setEntity(entity); response = client.execute(postRequest); } catch (Exception e) { e.printStackTrace(); return null; } StatusLine status = response.getStatusLine(); System.out.println("Response: " + status.getStatusCode() + " " + status.getReasonPhrase()); return response; }
From source file:tagtime.beeminder.BeeminderAPI.java
/** * Runs a put request./*from ww w.j a v a2 s . c o m*/ * @return Whether the request completed successfully. If this is * false, then Beeminder is probably inaccessible, and no * more requests should be sent for now. */ private static boolean runPutRequest(HttpClient client, TagTime tagTimeInstance, String dataURL, List<NameValuePair> postData) { //add the authorization token postData.add(new BasicNameValuePair("auth_token", tagTimeInstance.settings.getStringValue(SettingType.AUTH_TOKEN))); //build the request HttpPut putRequest = new HttpPut(dataURL); HttpResponse response; try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData); System.out.println("PUT " + dataURL + "?" + new BufferedReader(new InputStreamReader(entity.getContent())).readLine()); putRequest.setEntity(entity); response = client.execute(putRequest); } catch (Exception e) { e.printStackTrace(); return false; } StatusLine status = response.getStatusLine(); System.out.println("Response: " + status.getStatusCode() + " " + status.getReasonPhrase()); try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { e.printStackTrace(); } return true; }
From source file:com.gistlabs.mechanize.PageRequest.java
private Parameters extractParameters(final UrlEncodedFormEntity entity) { try {//from w ww . j a va 2 s . co m InputStream stream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); while (true) { String line = reader.readLine(); if (line != null) { if (content.length() > 0) content.append("\n"); content.append(line); } else break; } Parameters parameters = new Parameters(); for (NameValuePair param : URLEncodedUtils.parse(content.toString(), Charset.forName("UTF-8"))) parameters.add(param.getName(), param.getValue()); return parameters; } catch (IOException e) { throw MechanizeExceptionFactory.newException(e); } }
From source file:com.github.mjeanroy.junit.servers.client.impl.apache_http_client.ApacheHttpRequestTest.java
@Override protected void checkFormParam(HttpRequest httpRequest, String name, String value) throws Exception { Map<String, String> formParams = extract(httpRequest, "formParams"); assertThat(formParams).contains(entry(name, value)); checkHeader(httpRequest, "Content-Type", "application/x-www-form-urlencoded"); reset(client);//www . ja va2 s . c o m when(client.execute(any(HttpRequestBase.class))).thenReturn(mock(CloseableHttpResponse.class)); httpRequest.execute(); ArgumentCaptor<HttpEntityEnclosingRequest> rqCaptor = ArgumentCaptor .forClass(HttpEntityEnclosingRequest.class); verify(client).execute((HttpRequestBase) rqCaptor.capture()); HttpEntityEnclosingRequest rq = rqCaptor.getValue(); assertThat(rq.getEntity()).isNotNull().isExactlyInstanceOf(UrlEncodedFormEntity.class); UrlEncodedFormEntity entity = (UrlEncodedFormEntity) rq.getEntity(); StringWriter writer = new StringWriter(); IOUtils.copy(entity.getContent(), writer); String body = writer.toString(); String[] parts = body.split("&"); assertThat(parts).contains(name + "=" + value); assertThat(rq.getFirstHeader("Content-Type").getValue()).isEqualTo("application/x-www-form-urlencoded"); }
From source file:com.thoughtworks.go.util.HttpServiceTest.java
@Test public void shouldSetTheAcceptHeaderWhilePostingProperties() throws Exception { HttpPost post = mock(HttpPost.class); String url = "http://url"; when(httpClientFactory.createPost(url)).thenReturn(post); when(post.getURI()).thenReturn(new URI(url)); CloseableHttpResponse response = mock(CloseableHttpResponse.class); when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); when(httpClient.execute(post)).thenReturn(response); ArgumentCaptor<UrlEncodedFormEntity> entityCaptor = ArgumentCaptor.forClass(UrlEncodedFormEntity.class); service.postProperty(url, "value"); verify(post).setHeader("Confirm", "true"); verify(post).setEntity(entityCaptor.capture()); UrlEncodedFormEntity expected = new UrlEncodedFormEntity( Arrays.asList(new BasicNameValuePair("value", "value"))); UrlEncodedFormEntity actual = entityCaptor.getValue(); assertEquals(IOUtils.toString(expected.getContent()), IOUtils.toString(actual.getContent())); assertEquals(expected.getContentLength(), expected.getContentLength()); assertEquals(expected.getContentType(), expected.getContentType()); assertEquals(expected.getContentEncoding(), expected.getContentEncoding()); assertEquals(expected.isChunked(), expected.isChunked()); }
From source file:com.google.cloud.metrics.MetricsUtilsTest.java
@Test public void testBuildPostBodyMinimal() throws Exception { expect(mockRandom.nextLong()).andReturn(12345L).anyTimes(); replay(mockRandom);// w w w . j a v a 2 s . c o m Event event = Event.builder().setName("testEventName").setType("testEventType").setClientId("testClientId") .build(); UrlEncodedFormEntity entity = MetricsUtils.buildPostBody(event, "testAnalyticsId", mockRandom); verify(mockRandom); BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)); // We don't want to do an exact comparison to a specific string, because // we want the test to be order-agnostic. // Create a new list to ensure remove() is supported without making assumptions about Splitter. ArrayList<String> body = new ArrayList<>(Splitter.on("&").splitToList(reader.readLine())); // Verify static values. assertContainsAndRemove(body, "t=pageview"); assertContainsAndRemove(body, "v=1"); assertContainsAndRemove(body, "ni=0"); assertContainsAndRemove(body, "cd21=1"); // Verify dynamic values. assertContainsAndRemove(body, "z=12345"); assertContainsAndRemove(body, "tid=testAnalyticsId"); assertContainsAndRemove(body, "cd17=0"); assertContainsAndRemove(body, "cd16=0"); assertContainsAndRemove(body, "cd19=testEventType"); assertContainsAndRemove(body, "cd20=testEventName"); assertContainsAndRemove(body, "cid=testClientId"); // Verify encoding. assertContainsAndRemove(body, "dp=%2Fvirtual%2FtestEventType%2FtestEventName"); // Verify that the above values are the only values sent. assertThat(body).isEmpty(); }
From source file:com.google.cloud.metrics.MetricsUtilsTest.java
@Test public void testBuildPostBodyFull() throws Exception { expect(mockRandom.nextLong()).andReturn(12345L).anyTimes(); replay(mockRandom);/*from ww w . j ava 2 s .c om*/ Event event = Event.builder().setName("testEventName").setType("testEventType").setClientId("testClientId") .setIsUserSignedIn(true).setIsUserInternal(true).setIsUserTrialEligible(true) .setClientHostname("testClientHostname").setObjectType("testObjectType") .setProjectNumberHash("testProjectNumberHash").setBillingIdHash("testBillingIdHash") .addMetadata("key1,", "value1=\\").build(); UrlEncodedFormEntity entity = MetricsUtils.buildPostBody(event, "testAnalyticsId", mockRandom); verify(mockRandom); BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)); // We don't want to do an exact comparison to a specific string, because // we want the test to be order-agnostic. // Create a new list to ensure remove() is supported without making assumptions about Splitter. ArrayList<String> body = new ArrayList<>(Splitter.on("&").splitToList(reader.readLine())); // Verify static values. assertContainsAndRemove(body, "t=pageview"); assertContainsAndRemove(body, "v=1"); assertContainsAndRemove(body, "ni=0"); assertContainsAndRemove(body, "cd21=1"); // Verify dynamic values. assertContainsAndRemove(body, "z=12345"); assertContainsAndRemove(body, "tid=testAnalyticsId"); assertContainsAndRemove(body, "cd31=testProjectNumberHash"); assertContainsAndRemove(body, "cd18=testBillingIdHash"); assertContainsAndRemove(body, "cd17=1"); assertContainsAndRemove(body, "cd16=1"); assertContainsAndRemove(body, "cd22=1"); assertContainsAndRemove(body, "cd19=testEventType%2FtestObjectType"); assertContainsAndRemove(body, "cd20=testEventName"); assertContainsAndRemove(body, "cid=testClientId"); assertContainsAndRemove(body, "dh=testClientHostname"); // Verify encoding. assertContainsAndRemove(body, "dp=%2Fvirtual%2FtestEventType%2FtestObjectType%2FtestEventName"); assertContainsAndRemove(body, "dt=key1%5C%2C%3Dvalue1%5C%3D%5C%5C"); // Verify that the above values are the only values sent. assertThat(body).isEmpty(); }
From source file:code.google.restclient.client.HitterClient.java
private UrlEncodedFormEntity getUrlEncodedFormEntity(ViewRequest req) throws RCException { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); Map<String, String> params = req.getParams(); for (String paramName : params.keySet()) { formparams.add(new BasicNameValuePair(paramName, params.get(paramName))); }/*from ww w .j a v a 2 s .c o m*/ try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, RCConstants.DEFAULT_CHARSET); if (DEBUG_ENABLED) LOG.debug("getParamsPostEntity() - post body: " + streamToString(entity.getContent())); return entity; } catch (UnsupportedEncodingException e) { throw new RCException( "getParamsPostEntity(): Could not prepare params post entity due to unsupported encoding", e); } catch (IOException e) { throw new RCException("getParamsPostEntity(): request entity body could not be read"); } }
From source file:org.acein.wish.WishRequest.java
public WishResponse execute() throws Exception { String urlStr = this.getRequestURL() + this.getVersion() + this.path; String result = null;//from w w w . j a v a 2 s .co m CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; if (method.equalsIgnoreCase("GET")) { urlStr = urlStr + "?" + URLBuilder.httpBuildQuery((Hashtable) params, null);//http_build_query(params); System.out.println("http get:" + urlStr); HttpGet httpget = new HttpGet(urlStr); response = httpclient.execute(httpget); } else if (method.equalsIgnoreCase("POST")) { List<NameValuePair> formparams = new ArrayList<NameValuePair>(); //formparams.add(new BasicNameValuePair("param1", "value1")); //formparams.add(new BasicNameValuePair("param2", "value2")); Enumeration<String> en = params.keys(); while (en.hasMoreElements()) { String key = en.nextElement(); formparams.add(new BasicNameValuePair(key, params.get(key))); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8); HttpPost httppost = new HttpPost(urlStr); httppost.setEntity(entity); response = httpclient.execute(httppost); } else { Logger.getLogger("WishRequest").info("Invalid Submit Method."); } try { HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); // do something useful InputStreamReader isr = new InputStreamReader(instream); BufferedReader br = new BufferedReader(isr); result = br.readLine(); System.out.println(result); instream.close(); } } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } //JSONObject j = new JSONObject(respStr); //Hashtable decoded_result = new Hashtable(); // From json structure. return new WishResponse(this, /*decoded_result,*/ result); }