private String getContent(HttpResponse response) throws IOException { StringBuffer result = new StringBuffer(); try (BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) { String line; while ((line = rd.readLine()) != null) { result.append(line); } } return result.toString(); }
public HttpResponseAssert hasContentType(String contentType) { assertThat(actual.getEntity().getContentType().getValue()).containsIgnoringCase(contentType); return this; }
HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(urltofetch); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); InputStream inputStream = entity.getContent(); // write the file to whether you want it. }
public BufferedHttpEntity(final HttpEntity entity) throws IOException { super(entity); if (!entity.isRepeatable() || entity.getContentLength() < 0) { this.buffer = EntityUtils.toByteArray(entity); } else { this.buffer = null; } }
private static void appendHttpEntity(StringBuilder sb, HttpEntity e) { try { InputStream is = e.getContent(); String encoding = e.getContentEncoding().getValue(); System.out.println(encoding); BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName(encoding))); String str = null; while ((str = br.readLine()) != null) { sb.append(str); } br.close(); } catch (IOException ex) { LOG.severe(ex.getMessage()); } }
HttpClient httpclient = new DefaultHttpClient(); // Create HTTP Client HttpGet httpget = new HttpGet("http://yoururl.com"); // Set the action you want to do HttpResponse response = httpclient.execute(httpget); // Executeit HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); // Create an InputStream with the response BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) // Read line by line sb.append(line + "\n"); String resString = sb.toString(); // Result is here is.close(); // Close the stream
try { HttpPost postRequest = new HttpPost(url); postRequest.addHeader(header.getKey(), header.getValue()); postRequest.setEntity(entity); response = httpClient.execute(postRequest); br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((output = br.readLine()) != null) { sb.append(output); if (br != null) { try { br.close(); } catch (IOException e) { LOG.error("Failed to close resource", e);
/** Get the AWS instance type if applicable */ public String getInstanceType () { try { HttpGet get = new HttpGet(); // see http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html // This seems very much not EC2-like to hardwire an IP address for getting instance metadata, // but that's how it's done. get.setURI(new URI("http://169.254.169.254/latest/meta-data/instance-type")); get.setConfig(RequestConfig.custom() .setConnectTimeout(2000) .setSocketTimeout(2000) .build() ); HttpResponse res = httpClient.execute(get); InputStream is = res.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String type = reader.readLine().trim(); reader.close(); return type; } catch (Exception e) { LOG.info("could not retrieve EC2 instance type, you may be running outside of EC2."); return null; } }
if (response.getEntity().getContentType().getValue().contains("charset=")) { String contentType = response.getEntity().getContentType().getValue(); charset = contentType.substring(contentType.lastIndexOf("=") + 1); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset)); String line; while ((line = in.readLine()) != null) { buffer.add(line); in.close(); response.close(); return buffer;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService); // Depends on your web service httppost.setHeader("Content-type", "application/json"); InputStream inputStream = null; String result = null; try { HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); inputStream = entity.getContent(); // json is UTF-8 by default BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (Exception e) { // Oops } finally { try{if(inputStream != null)inputStream.close();}catch(Exception squish){} }
@Override public void run() throws IOException { org.apache.http.HttpResponse httpResponse = helper.getResponse(remoteUrl("/dir/dir.response")); String value = httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(); assertThat(value, is("text/plain")); String content = CharStreams.toString(new InputStreamReader(httpResponse.getEntity().getContent())); assertThat(content, is("response from dir")); } });
protected InputStreamReader openStream( String encoding, HttpResponse httpResponse ) throws Exception { if ( !Utils.isEmpty( encoding ) ) { return new InputStreamReader( httpResponse.getEntity().getContent(), encoding ); } else { return new InputStreamReader( httpResponse.getEntity().getContent() ); } }
@Test public void testExecute() throws IOException { AndroidHttpClient client = AndroidHttpClient.newInstance("foo"); FakeHttp.addPendingHttpResponse(200, "foo"); HttpResponse resp = client.execute(new HttpGet("/foo")); assertThat(resp.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(CharStreams.toString(new InputStreamReader(resp.getEntity().getContent(), UTF_8))) .isEqualTo("foo"); } }
@Test public void shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams() throws Exception { TestHttpResponse testHttpResponse = new TestHttpResponse(200, "a cheery response body"); FakeHttp.addHttpResponseRule("http://some.uri", testHttpResponse); assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isTrue(); HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null); InputStream getResponseStream = getResponse.getEntity().getContent(); assertThat(CharStreams.toString(new InputStreamReader(getResponseStream, UTF_8))) .isEqualTo("a cheery response body"); assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isFalse(); HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null); InputStream postResponseStream = postResponse.getEntity().getContent(); assertThat(CharStreams.toString(new InputStreamReader(postResponseStream, UTF_8))) .isEqualTo("a cheery response body"); assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isFalse(); getResponseStream.close(); assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isFalse(); postResponseStream.close(); assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed()).isTrue(); }
@Test public void shouldParameteriseUrisInRelationshipRepresentationWithoutHostHeaderUsingRequestUri() throws Exception { HttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet( getServerUri() + "db/data/relationship/" + likes ); httpget.setHeader( "Accept", "application/json" ); HttpResponse response = httpclient.execute( httpget ); HttpEntity entity = response.getEntity(); String entityBody = IOUtils.toString( entity.getContent(), StandardCharsets.UTF_8 ); assertThat( entityBody, containsString( getServerUri() + "db/data/relationship/" + likes ) ); } finally { httpclient.getConnectionManager().shutdown(); } }
private JSONObject readJSONObjectFromUrlPOST(String urlString, Map<String, String> headers, String payload) throws IOException, JSONException { HttpClient httpClient = openConnection(); HttpPost request = new HttpPost(urlString); for (Map.Entry<String, String> entry : headers.entrySet()) { request.addHeader(entry.getKey(), entry.getValue()); } HttpEntity httpEntity = new StringEntity(payload); request.setEntity(httpEntity); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase()); } InputStream content = response.getEntity().getContent(); return readAllIntoJSONObject(content); }
public static HttpResult httpPostLarge(String url, Map<String, String> headers, String content) { try { HttpClientBuilder builder = HttpClients.custom(); builder.setUserAgent(UtilsAndCommons.SERVER_VERSION); builder.setConnectionTimeToLive(500, TimeUnit.MILLISECONDS); CloseableHttpClient httpClient = builder.build(); HttpPost httpost = new HttpPost(url); for (Map.Entry<String, String> entry : headers.entrySet()) { httpost.setHeader(entry.getKey(), entry.getValue()); } httpost.setEntity(new StringEntity(content, ContentType.create("application/json", "UTF-8"))); HttpResponse response = httpClient.execute(httpost); HttpEntity entity = response.getEntity(); HeaderElement[] headerElements = entity.getContentType().getElements(); String charset = headerElements[0].getParameterByName("charset").getValue(); return new HttpResult(response.getStatusLine().getStatusCode(), IOUtils.toString(entity.getContent(), charset), Collections.<String, String>emptyMap()); } catch (Exception e) { return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap()); } }
HttpHost proxy = new HttpHost("ip address",port number); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy); HttpPost httpost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("param name", param)); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.ISO_8859_1)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); System.out.println("Request Handled?: " + response.getStatusLine()); InputStream in = entity.getContent(); httpclient.getConnectionManager().shutdown();
public static HttpResult httpPost(String url, List<String> headers, Map<String, String> paramValues, String encoding) { try { HttpPost httpost = new HttpPost(url); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000).setConnectTimeout(5000).setSocketTimeout(5000).setRedirectsEnabled(true).setMaxRedirects(5).build(); httpost.setConfig(requestConfig); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : paramValues.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpost.setEntity(new UrlEncodedFormEntity(nvps, encoding)); HttpResponse response = postClient.execute(httpost); HttpEntity entity = response.getEntity(); String charset = encoding; if (entity.getContentType() != null) { HeaderElement[] headerElements = entity.getContentType().getElements(); if (headerElements != null && headerElements.length > 0 && headerElements[0] != null && headerElements[0].getParameterByName("charset") != null) { charset = headerElements[0].getParameterByName("charset").getValue(); } } return new HttpResult(response.getStatusLine().getStatusCode(), IOUtils.toString(entity.getContent(), charset), Collections.<String, String>emptyMap()); } catch (Throwable e) { return new HttpResult(500, e.toString(), Collections.<String, String>emptyMap()); } }
HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/"); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("param-1", "12345")); params.add(new BasicNameValuePair("param-2", "Hello!")); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); //Execute and get the response. HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { // do something useful } finally { instream.close(); } }