@Test public void testTwoInclude() throws Exception { HttpGet httpGet = new HttpGet( "http://localhost:" + ourPort + "/Patient?name=Hello&_include=foo&_include=bar&_pretty=true"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); assertEquals(1, bundle.size()); Patient p = bundle.getResources(Patient.class).get(0); assertEquals(2, p.getName().size()); assertEquals("Hello", p.getId().getIdPart()); Set<String> values = new HashSet<String>(); values.add(p.getName().get(0).getFamilyFirstRep().getValue()); values.add(p.getName().get(1).getFamilyFirstRep().getValue()); assertThat(values, containsInAnyOrder("foo", "bar")); }
@Test public void testKeepAlive() throws Exception { String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14"; HttpPut request = new HttpPut(url); request.setHeader("Connection", "keep-alive"); HttpGet getRequest = new HttpGet(url); getRequest.setHeader("Connection", "keep-alive"); for (int i = 0; i < 100; i++) { request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(request)) { assertEquals(200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); } try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) { assertEquals(200, response2.getStatusLine().getStatusCode()); List<String> values = consumeJsonPinValues(response2); assertEquals(1, values.size()); assertEquals(String.valueOf(i), values.get(0)); } } }
@Test public void basicAuth() throws Exception { setupRealmUser(); KerberosContainer kdc = startKdc(); configureSso(kdc, true); // I am not able to get the basic auth to work in FF 45.3.0, so using HttpClient instead // org.openqa.selenium.UnsupportedCommandException: Unrecognized command: POST // /session/466a800f-eaf8-40cf-a9e8-815f5a6e3c32/alert/credentials // alert.setCredentials(new UserAndPassword("user", "ATH")); CloseableHttpClient httpClient = getBadassHttpClient(); // No credentials provided assertUnauthenticatedRequestIsRejected(httpClient); // Correct credentials provided HttpGet get = new HttpGet(jenkins.url.toExternalForm() + "/whoAmI"); get.setHeader("Authorization", "Basic " + Base64.encode("user:ATH".getBytes())); CloseableHttpResponse response = httpClient.execute(get); String phrase = response.getStatusLine().getReasonPhrase(); String out = IOUtils.toString(response.getEntity().getContent()); assertThat(phrase + ": " + out, out, containsString("Full Name")); assertThat(phrase + ": " + out, out, containsString("Granted Authorities: authenticated")); assertEquals(phrase + ": " + out, "OK", phrase); // Incorrect credentials provided get = new HttpGet(jenkins.url.toExternalForm() + "/whoAmI"); get.setHeader("Authorization", "Basic " + Base64.encode("user:WRONG_PASSWD".getBytes())); response = httpClient.execute(get); assertEquals( "Invalid password/token for user: user", response.getStatusLine().getReasonPhrase()); }
@Test public void testUpdateWithTagWithSchemeAndLabel() throws Exception { DiagnosticReport dr = new DiagnosticReport(); dr.setId("001"); dr.addCodedDiagnosis().addCoding().setCode("AAA"); HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001"); httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\""); httpPost.setEntity( new StringEntity( ourCtx.newXmlParser().encodeResourceToString(dr), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); CloseableHttpResponse status = ourClient.execute(httpPost); assertEquals(1, ourReportProvider.getLastTags().size()); assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0)); IOUtils.closeQuietly(status.getEntity().getContent()); httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001"); httpPost.addHeader("Category", "Dog; scheme=\"http://foo\"; label=\"aaaa\"; "); httpPost.setEntity( new StringEntity( ourCtx.newXmlParser().encodeResourceToString(dr), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); status = ourClient.execute(httpPost); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(1, ourReportProvider.getLastTags().size()); assertEquals(new Tag("http://foo", "Dog", "aaaa"), ourReportProvider.getLastTags().get(0)); }
@Test public void testSingletonService(@ArquillianResource(MyServiceServlet.class) URL baseURL) throws IOException, URISyntaxException { // URLs look like "http://IP:PORT/singleton/service" URI defaultURI = MyServiceServlet.createURI(baseURL, MyServiceActivator.DEFAULT_SERVICE_NAME); URI quorumURI = MyServiceServlet.createURI(baseURL, MyServiceActivator.QUORUM_SERVICE_NAME); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { HttpResponse response = client.execute(new HttpGet(defaultURI)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue()); } finally { HttpClientUtils.closeQuietly(response); } // Service should be started regardless of whether a quorum was required. response = client.execute(new HttpGet(quorumURI)); try { assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(NODE_1, response.getFirstHeader("node").getValue()); } finally { HttpClientUtils.closeQuietly(response); } } }
@Override public String getChannels(String serverUrl, boolean premium) throws ClientProtocolException, UnsupportedEncodingException, IOException { String playLIst = null; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); // CloseableHttpClient httpClient = HttpClients.custom().setRoutePlanner(routePlanner).build(); HttpResponse login = httpClient.execute(getVideoStarLogin()); EntityUtils.consume(login.getEntity()); if (login.getStatusLine().getStatusCode() == 302) { HttpResponse getChannel = httpClient.execute(getChannelsRequest(login)); if (getChannel.getStatusLine().getStatusCode() == 200) { VideoStarChannelRequest channels = jsonService.parseVideoStarChannels(EntityUtils.toString(getChannel.getEntity())); if (channels != null && channels.getStatus().equals("ok")) { return prepareChannelList(channels, serverUrl, premium); // return channelsString; } else if (channels != null && channels.getStatus().equals("error")) { // TODO } else { // TODO } } } return playLIst; }
public String unTag(NewTagModel untag) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + untag.get_id()); oldTagGet.addHeader(authHeaderKey, authHeaderValue); oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue); oldTagGet.addHeader(contentHeaderKey, contentHeaderValue); HttpResponse oldTagResp = httpclient.execute(oldTagGet); Gson gson = new Gson(); TagModel updatedtag = gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class); httpclient.close(); updatedtag.getTagged().remove(untag.getUsername()); LOGGER.info(untag.get_id() + " is untagging " + untag.getUsername()); HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + untag.get_id()); updatedTagPut.addHeader(authHeaderKey, authHeaderValue); updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue); updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue); updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag))); httpclient = HttpClients.createDefault(); HttpResponse updatedTagResp = httpclient.execute(updatedTagPut); if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) { String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity()); httpclient.close(); return updatedTagEntity; } httpclient.close(); return successJson; } catch (Exception e) { e.printStackTrace(); return failJson; } }
public static void test1() throws ClientProtocolException, IOException { // httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("username", "")); formparams.add(new BasicNameValuePair("areacode", "86")); formparams.add(new BasicNameValuePair("telephone", "18782071219")); formparams.add(new BasicNameValuePair("remember_me", "1")); formparams.add(new BasicNameValuePair("password", Encoding.MD5("199337").toUpperCase())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost httppost = new HttpPost("http://xueqiu.com/user/login"); httppost.setEntity(entity); httppost.setHeader("X-Requested-With", "XMLHttpRequest"); CloseableHttpResponse httpResponse = httpClient.execute(httppost); HttpEntity entity1 = httpResponse.getEntity(); if (entity1 != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8")); System.out.println("--------------------------------------"); } setCookieStore(httpResponse); HttpGet httpGet = new HttpGet( "http://xueqiu.com/financial_product/query.json?page=1&size=3&order=desc&orderby=SALEBEGINDATE&status=1&_=1439607538138"); httpResponse = httpClient.execute(httpGet); entity1 = httpResponse.getEntity(); if (entity1 != null) { System.out.println("--------------------------------------"); System.out.println("Response content: " + EntityUtils.toString(entity1, "UTF-8")); System.out.println("--------------------------------------"); } }
@Test public void testSpecificallyNamedQueryGetsPrecedence() throws Exception { HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?AAA=123"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); Bundle bundle = ourCtx.newXmlParser().parseBundle(responseContent); assertEquals(1, bundle.getEntries().size()); Patient p = bundle.getResources(Patient.class).get(0); assertEquals("AAA", p.getIdentifierFirstRep().getValue().getValue()); // Now the named query httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient?_query=findPatientByAAA&AAA=123"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); bundle = ourCtx.newXmlParser().parseBundle(responseContent); assertEquals(1, bundle.getEntries().size()); p = bundle.getResources(Patient.class).get(0); assertEquals("AAANamed", p.getIdentifierFirstRep().getValue().getValue()); }
@RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST) public String formSubmit(@ModelAttribute User user, Model model) throws MalformedURLException, IOException { model.addAttribute("user", user); HttpPost post = new HttpPost( "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/"); BasicCookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName())); nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName())); nameValuePairs.add(new BasicNameValuePair("email", user.getEmail())); nameValuePairs.add(new BasicNameValuePair("password", user.getPassword())); nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation())); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(post); response = httpclient.execute(post); System.out.println("Status code is " + response.getStatusLine().getStatusCode()); System.out.println(response.toString()); System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++"); System.out.println(response.getFirstHeader("Location")); HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); EntityUtils.consume(response.getEntity()); /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html"); FileWriter fileWriter = new FileWriter(newTextFile); fileWriter.write(response.toString()); fileWriter.close();*/ return "result"; }
@Test @OperateOnDeployment(DEPLOYMENT_1) public void testSerialized(@ArquillianResource(SimpleServlet.class) URL baseURL) throws IOException, URISyntaxException { // returns the URL of the deployment (http://127.0.0.1:8180/distributable) URI uri = SimpleServlet.createURI(baseURL); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { HttpResponse response = client.execute(new HttpGet(uri)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue())); Assert.assertFalse(Boolean.valueOf(response.getFirstHeader("serialized").getValue())); } finally { HttpClientUtils.closeQuietly(response); } response = client.execute(new HttpGet(uri)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue())); // This won't be true unless we have somewhere to which to replicate Assert.assertTrue(Boolean.valueOf(response.getFirstHeader("serialized").getValue())); } finally { HttpClientUtils.closeQuietly(response); } } }
public String updateTagged(NewTagModel newtag) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // get old tagged from cloudant // in NewTagModel - get_id() returns person initiating tag - getUsername() returns person to // tag HttpGet oldTagGet = new HttpGet(cloudantURI + "/tag/" + newtag.get_id()); oldTagGet.addHeader(authHeaderKey, authHeaderValue); oldTagGet.addHeader(acceptHeaderKey, acceptHeaderValue); oldTagGet.addHeader(contentHeaderKey, contentHeaderValue); HttpResponse oldTagResp = httpclient.execute(oldTagGet); Gson gson = new Gson(); TagModel updatedtag = gson.fromJson(EntityUtils.toString(oldTagResp.getEntity()), TagModel.class); httpclient.close(); // check for and don't allow retagging - currently front-end design shouldn't allow for this // but needs to be checked on server side as well if (updatedtag.getTagged().contains(newtag.getUsername())) { LOGGER.info( newtag.getUsername() + " already exists in tagged list for " + updatedtag.get_id()); return alreadyTaggedJson; } // update array of tagged in updatedtag and update entry in cloudant updatedtag.getTagged().add(newtag.getUsername()); HttpPut updatedTagPut = new HttpPut(cloudantURI + "/tag/" + newtag.get_id()); updatedTagPut.addHeader(authHeaderKey, authHeaderValue); updatedTagPut.addHeader(acceptHeaderKey, acceptHeaderValue); updatedTagPut.addHeader(contentHeaderKey, contentHeaderValue); updatedTagPut.setEntity(new StringEntity(gson.toJson(updatedtag))); httpclient = HttpClients.createDefault(); HttpResponse updatedTagResp = httpclient.execute(updatedTagPut); if (!(updatedTagResp.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)) { String updatedTagEntity = EntityUtils.toString(updatedTagResp.getEntity()); httpclient.close(); return updatedTagEntity; } httpclient.close(); LOGGER.info(newtag.get_id() + " tagged " + newtag.getUsername()); return successJson; } catch (Exception e) { try { httpclient.close(); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); return failJson; } }
@Test public void testFileSystemGet() throws Exception { final File barFile = new File(tmpDir, "bar.html"); final String expectedContentA = "<html/>"; final String expectedContentB = "<html><body/></html>"; Files.write(barFile.toPath(), expectedContentA.getBytes(StandardCharsets.UTF_8)); try (CloseableHttpClient hc = HttpClients.createMinimal()) { final String lastModified; HttpUriRequest req = new HttpGet(newUri("/fs/bar.html")); try (CloseableHttpResponse res = hc.execute(req)) { lastModified = assert200Ok(res, "text/html", expectedContentA); } // Test if the 'If-Modified-Since' header works as expected. req = new HttpGet(newUri("/fs/bar.html")); req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); try (CloseableHttpResponse res = hc.execute(req)) { assert304NotModified(res, lastModified, "text/html"); } // Test if the 'If-Modified-Since' header works as expected after the file is modified. req = new HttpGet(newUri("/fs/bar.html")); req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); // HTTP-date has no sub-second precision; wait until the current second changes. Thread.sleep(1000); Files.write(barFile.toPath(), expectedContentB.getBytes(StandardCharsets.UTF_8)); try (CloseableHttpResponse res = hc.execute(req)) { final String newLastModified = assert200Ok(res, "text/html", expectedContentB); // Ensure that the 'Last-Modified' header did not change. assertThat(newLastModified, is(not(lastModified))); } // Test if the cache detects the file removal correctly. final boolean deleted = barFile.delete(); assertThat(deleted, is(true)); req = new HttpGet(newUri("/fs/bar.html")); req.setHeader(HttpHeaders.IF_MODIFIED_SINCE, currentHttpDate()); req.setHeader(HttpHeaders.CONNECTION, "close"); try (CloseableHttpResponse res = hc.execute(req)) { assert404NotFound(res); } } }
public void getIPTShows() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); CloseableHttpResponse response = null; String pageURL = "https://www.iptorrents.com"; try { HttpGet httpGet = new HttpGet(pageURL); httpGet.addHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"); response = httpClient.execute(httpGet); response.removeHeaders("Transfer-Encoding"); HttpPost thePost = new HttpPost(pageURL + "?username=mcpchelper81&password=ru68ce48&php="); thePost.setHeaders(response.getAllHeaders()); response.close(); response = null; response = httpClient.execute(thePost); httpGet = new HttpGet("https://www.iptorrents.com/t?5"); httpGet.setHeaders(response.getHeaders("set-cookie")); httpGet.addHeader( "accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpGet.addHeader("accept-encoding", "gzip, deflate, sdch"); httpGet.addHeader("accept-language", "en-US,en;q=0.8"); httpGet.addHeader("dnt", "1"); httpGet.addHeader("upgrade-insecure-requests", "1"); httpGet.addHeader( "user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"); response.close(); response = null; response = httpClient.execute(httpGet); Header contentType = response.getFirstHeader("Content-Type"); HttpEntity httpEntity = response.getEntity(); String[] contentArray = contentType.getValue().split(";"); String charset = "UTF-8"; if (contentArray.length > 1 && contentArray[1].contains("=")) { charset = contentArray[1].trim().split("=")[1]; } Document pageDoc = Jsoup.parse(httpEntity.getContent(), charset, httpGet.getURI().getPath()); Elements results = pageDoc.getElementsByClass("torrents"); response.close(); Elements rawShowObjects = results.select("tr"); IPTToTvShowEpisode makeShows = new IPTToTvShowEpisode(); List<TvShowEpisode> theShows = makeShows.makeTSEBeans(rawShowObjects); DBActions.insertIPTTvEpisodes(theShows, "https://www.iptorrents.com/t?5"); } catch (MalformedURLException MURLe) { MURLe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
@Test @OperateOnDeployment(DEPLOYMENT_2) // For change, operate on the 2nd deployment first public void testSessionReplication( @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SimpleServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException { URI url1 = SimpleServlet.createURI(baseURL1); URI url2 = SimpleServlet.createURI(baseURL2); try (CloseableHttpClient client = TestHttpClientUtils.promiscuousCookieHttpClient()) { HttpResponse response = client.execute(new HttpGet(url1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(1, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Lets do this twice to have more debug info if failover is slow. response = client.execute(new HttpGet(url1)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(2, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Lets wait for the session to replicate waitForReplication(GRACE_TIME_TO_REPLICATE); // Now check on the 2nd server response = client.execute(new HttpGet(url2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(3, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } // Lets do one more check. response = client.execute(new HttpGet(url2)); try { Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(4, Integer.parseInt(response.getFirstHeader("value").getValue())); } finally { HttpClientUtils.closeQuietly(response); } } }
@Test public void testApacheProxyAddressStrategy() throws Exception { ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttp()); HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("<family value=\"FAMILY\"")); assertThat( responseContent, containsString("<fullUrl value=\"http://localhost:" + ourPort + "/Patient/1\"/>")); ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); httpGet.addHeader("x-forwarded-host", "foo.com"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("<family value=\"FAMILY\"")); assertThat(responseContent, containsString("<fullUrl value=\"http://foo.com/Patient/1\"/>")); ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttps()); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); httpGet.addHeader("x-forwarded-host", "foo.com"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("<family value=\"FAMILY\"")); assertThat(responseContent, containsString("<fullUrl value=\"https://foo.com/Patient/1\"/>")); ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false)); httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient"); httpGet.addHeader("x-forwarded-host", "foo.com"); httpGet.addHeader("x-forwarded-proto", "https"); status = ourClient.execute(httpGet); responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info(responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertThat(responseContent, containsString("<family value=\"FAMILY\"")); assertThat(responseContent, containsString("<fullUrl value=\"https://foo.com/Patient/1\"/>")); }
public static String sendToRockBlockHttp( String destImei, String username, String password, byte[] data) throws HttpException, IOException { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("https://secure.rock7mobile.com/rockblock/MT"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("imei", destImei)); urlParameters.add(new BasicNameValuePair("username", username)); urlParameters.add(new BasicNameValuePair("password", password)); urlParameters.add(new BasicNameValuePair("data", ByteUtil.encodeToHex(data))); post.setEntity(new UrlEncodedFormEntity(urlParameters)); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); HttpResponse response = client.execute(post); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } try { client.close(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); }
@Test public static void depositeDetailTest() throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost post = new HttpPost("http://192.168.2.111:8578/service?channel=QueryNoticePage"); List<NameValuePair> list = new ArrayList<NameValuePair>(); list.add(new BasicNameValuePair("platformId", "82044")); list.add(new BasicNameValuePair("appKey", "1")); post.setEntity(new UrlEncodedFormEntity(list)); CloseableHttpResponse response = httpclient.execute(post); try { System.out.println(response.getStatusLine()); HttpEntity entity2 = response.getEntity(); String entity = EntityUtils.toString(entity2); if (entity.contains("code\":\"0")) { System.out.println("Success!"); System.out.println("response content:" + entity); } else { System.out.println("Failure!"); System.out.println("response content:" + entity); AssertJUnit.fail(entity); } } finally { response.close(); } } finally { httpclient.close(); } }
@Test public void testUpdateWithoutConditionalUrl() throws Exception { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/2"); httpPost.setEntity( new StringEntity( ourCtx.newXmlParser().encodeResourceToString(patient), ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); ourLog.info("Response was:\n{}", responseContent); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals( "http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("location").getValue()); assertEquals( "http://localhost:" + ourPort + "/Patient/001/_history/002", status.getFirstHeader("content-location").getValue()); assertEquals("Patient/2", new IdType(ourLastId).toUnqualified().getValue()); assertEquals("Patient/2", ourLastIdParam.toUnqualified().getValue()); assertNull(ourLastConditionalUrl); }
public static String uploadMaterial( String url, Map<String, String> params, String formDataName, File file) { client = getHttpClientInstance(); URI uri = generateURLParams(url, params); HttpPost post = new HttpPost(uri); post.setConfig(requestConfig); ContentBody contentBody = new FileBody(file); HttpEntity reqestEntity = MultipartEntityBuilder.create().addPart(formDataName, contentBody).build(); post.setEntity(reqestEntity); String responseStr = null; CloseableHttpResponse httpResponse = null; try { httpResponse = client.execute(post); responseStr = generateHttpResponse(httpResponse); } catch (IOException e) { } finally { if (null != httpResponse) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } } return responseStr; }
public static String doPost(String url, Map<String, String> params, String jsonStr) { logger.info(jsonStr); client = getHttpClientInstance(); URI uri = generateURLParams(url, params); HttpPost post = new HttpPost(uri); post.setConfig(requestConfig); String responseStr = null; CloseableHttpResponse httpResponse = null; try { HttpEntity entity = new StringEntity(jsonStr, DEFAULT_CHARSET); post.setEntity(entity); post.setHeader("Content-Type", "application/json"); httpResponse = client.execute(post); responseStr = generateHttpResponse(httpResponse); } catch (IOException e) { e.printStackTrace(); } finally { if (null != httpResponse) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } } return responseStr; }
public static String sendSSLPost(String url) throws ClientProtocolException, IOException { String line = null; StringBuilder stringBuilder = new StringBuilder(); CloseableHttpClient httpClient = HttpClientUtil.createSSLClientDefault(); HttpGet getdd = new HttpGet(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-type", "application/x-www-form-urlencoded"); // httpPost.setEntity(new StringEntity(JSON.toJSONString(param), "UTF-8")); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == 200) { org.apache.http.HttpEntity httpEntity = response.getEntity(); if (httpEntity != null) { try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8 * 1024); while ((line = bufferedReader.readLine()) != null) { stringBuilder.append(line); } } catch (Exception e) { } } } return stringBuilder.toString(); }
@Test public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws ClientProtocolException, IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, "application/xml"); response = instance.execute(request); }
public void propfind(HttpPropfind.Mode mode) throws URISyntaxException, IOException, DavException, HttpException { @Cleanup CloseableHttpResponse response = null; // processMultiStatus() requires knowledge of the actual content location, // so we have to handle redirections manually and create a new request for the new location for (int i = context.getRequestConfig().getMaxRedirects(); i > 0; i--) { HttpPropfind propfind = new HttpPropfind(location, mode); response = httpClient.execute(propfind, context); if (response.getStatusLine().getStatusCode() / 100 == 3) { location = DavRedirectStrategy.getLocation(propfind, response, context); Log.i(TAG, "Redirection on PROPFIND; trying again at new content URL: " + location); // don't forget to throw away the unneeded response content HttpEntity entity = response.getEntity(); if (entity != null) { @Cleanup InputStream content = entity.getContent(); } } else break; // answer was NOT a redirection, continue } if (response == null) throw new DavNoContentException(); checkResponse(response); // will also handle Content-Location processMultiStatus(response); }
/** * * Recreates POST from web interface, sends it to yodaQA and gets response * * @param address Address of yodaQA * @param request POST from web interface containing question * @param concepts More concepts to send to yodaQA * @return response of yodaQA */ public String getPOSTResponse( String address, Request request, String question, ArrayDeque<Concept> concepts, String artificialClue) { String result = ""; try { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(address); PostRecreator postRecreator = new PostRecreator(); httpPost = postRecreator.recreatePost(httpPost, request, question, concepts, artificialClue); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); String inputLine; StringBuffer postResponse = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { postResponse.append(inputLine); } reader.close(); httpClient.close(); result = postResponse.toString(); } catch (Exception e) { e.printStackTrace(); } return result; }
// 底层请求打印页面 private byte[] sendRequest(HttpRequestBase request) throws Exception { CloseableHttpResponse response = httpclient.execute(request); // 设置超时 setTimeOut(request, 5000); // 获取返回的状态列表 StatusLine statusLine = response.getStatusLine(); System.out.println("StatusLine : " + statusLine); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { try { // 获取response entity HttpEntity entity = response.getEntity(); System.out.println("getContentType : " + entity.getContentType().getValue()); System.out.println("getContentEncoding : " + entity.getContentEncoding().getValue()); // 读取响应内容 byte[] responseBody = EntityUtils.toByteArray(entity); // 关闭响应流 EntityUtils.consume(entity); return responseBody; } finally { response.close(); } } return null; }
@Test public void multiple_headers_with_the_same_name_are_processed_successfully() throws Exception { final CloseableHttpClient client = mock(CloseableHttpClient.class); final DropwizardApacheConnector dropwizardApacheConnector = new DropwizardApacheConnector(client, null, false); final Header[] apacheHeaders = { new BasicHeader("Set-Cookie", "test1"), new BasicHeader("Set-Cookie", "test2") }; final CloseableHttpResponse apacheResponse = mock(CloseableHttpResponse.class); when(apacheResponse.getStatusLine()) .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); when(apacheResponse.getAllHeaders()).thenReturn(apacheHeaders); when(client.execute(Matchers.any())).thenReturn(apacheResponse); final ClientRequest jerseyRequest = mock(ClientRequest.class); when(jerseyRequest.getUri()).thenReturn(URI.create("http://localhost")); when(jerseyRequest.getMethod()).thenReturn("GET"); when(jerseyRequest.getHeaders()).thenReturn(new MultivaluedHashMap<>()); final ClientResponse jerseyResponse = dropwizardApacheConnector.apply(jerseyRequest); assertThat(jerseyResponse.getStatus()) .isEqualTo(apacheResponse.getStatusLine().getStatusCode()); }
@Test public void testIIncludedResourcesNonContainedInExtensionJson() throws Exception { HttpGet httpGet = new HttpGet( "http://localhost:" + ourPort + "/Patient?_query=extInclude&_pretty=true&_format=json"); HttpResponse status = ourClient.execute(httpGet); String responseContent = IOUtils.toString(status.getEntity().getContent()); IOUtils.closeQuietly(status.getEntity().getContent()); assertEquals(200, status.getStatusLine().getStatusCode()); Bundle bundle = ourCtx.newJsonParser().parseBundle(responseContent); ourLog.info(responseContent); assertEquals(3, bundle.size()); assertEquals( new IdDt("Patient/p1"), bundle.toListOfResources().get(0).getId().toUnqualifiedVersionless()); assertEquals( new IdDt("Patient/p2"), bundle.toListOfResources().get(1).getId().toUnqualifiedVersionless()); assertEquals( new IdDt("Organization/o1"), bundle.toListOfResources().get(2).getId().toUnqualifiedVersionless()); assertEquals( BundleEntrySearchModeEnum.INCLUDE, bundle.getEntries().get(2).getSearchMode().getValueAsEnum()); Patient p1 = (Patient) bundle.toListOfResources().get(0); assertEquals(0, p1.getContained().getContainedResources().size()); Patient p2 = (Patient) bundle.toListOfResources().get(1); assertEquals(0, p2.getContained().getContainedResources().size()); }
@Override public boolean load(BuildCacheKey key, BuildCacheEntryReader reader) throws BuildCacheException { final URI uri = root.resolve("./" + key.getHashCode()); HttpGet httpGet = new HttpGet(uri); CloseableHttpResponse response = null; try { response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Response for GET {}: {}", uri, statusLine); } int statusCode = statusLine.getStatusCode(); if (statusCode >= 200 && statusCode < 300) { reader.readFrom(response.getEntity().getContent()); return true; } else if (statusCode == 404) { return false; } else { throw new BuildCacheException( String.format( "HTTP cache returned status %d: %s for key '%s' from %s", statusCode, statusLine.getReasonPhrase(), key, getDescription())); } } catch (IOException e) { throw new BuildCacheException( String.format("loading key '%s' from %s", key, getDescription()), e); } finally { HttpClientUtils.closeQuietly(response); } }
public final void run() { proccess(); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost( "https://api.telegram.org/bot115447632:AAGiH7bX_7dpywsXWONvsJPESQe-N7EmcQI/sendMessage"); httpPost.addHeader("Content-type", "application/x-www-form-urlencoded"); httpPost.addHeader("charset", "UTF-8"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("chat_id", String.valueOf(update.message.chat.id))); urlParameters.add(new BasicNameValuePair("text", mensagem)); if (teclado != null) urlParameters.add(new BasicNameValuePair("reply_markup", teclado)); if (mensagemRetornoID != null) urlParameters.add( new BasicNameValuePair("reply_to_message_id", mensagemRetornoID.toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); httpclient.execute(httpPost); } catch (IOException e) { e.printStackTrace(); } }