@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")); }
/** * Evaluate the status of the HTTP Request and return the appropriate response. * * @param requestResult * @return * @throws Exception */ public JSONObject checkAndRetrieveResponse(HttpResponse requestResult) throws Exception { int requestStatusCode = requestResult.getStatusLine().getStatusCode(); if (requestStatusCode != 200 && requestStatusCode != 201 && requestStatusCode != 204) { JSONObject unsuccessfulOperation = new JSONObject(); // unsuccessfulOperation.put("OServer responded with status code: " + // Integer.toString(requestStatusCode) + " . " + // requestResult.getStatusLine().getReasonPhrase(), requestStatusCode); // return unsuccessfulOperation; throw new Exception( "Server responded with status code: " + Integer.toString(requestStatusCode) + " . " + requestResult.getStatusLine().getReasonPhrase()); } else { JSONObject successfulOperation = new JSONObject(); successfulOperation.put("Operation finished successfully.", requestStatusCode); if (requestResult.getEntity() == null) { return successfulOperation; } String JSONString = EntityUtils.toString(requestResult.getEntity()); JSONObject responseJSON = new JSONObject(JSONString); return responseJSON; } }
@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()); }
@Test public void testServerReturnsWrongVersionForDstu2() throws Exception { Conformance conf = new Conformance(); conf.setFhirVersion("0.80"); String msg = myCtx.newXmlParser().encodeResourceToString(conf); ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpResponse.getStatusLine()) .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); when(myHttpResponse.getEntity().getContentType()) .thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); when(myHttpResponse.getEntity().getContent()) .thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"))); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE); try { myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123")); fail(); } catch (FhirClientInappropriateForServerException e) { String out = e.toString(); String want = "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2 (via the FhirContext)"; ourLog.info(out); ourLog.info(want); assertThat(out, containsString(want)); } }
@Override protected JSONArray doInBackground(Map<String, String>... uri) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; JSONArray finalResult = null; try { response = httpclient.execute(new HttpGet(uri[0].get("host"))); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); JSONTokener tokener = new JSONTokener(json); try { finalResult = new JSONArray(tokener); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { // TODO Handle problems.. } catch (IOException e) { // TODO Handle problems.. } return finalResult; }
@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"; }
private HttpStatus commit(HttpUriRequest method) throws IOException { HttpStatus status; HttpClient httpclient = createHttpClient(); // reduce the TIME_WAIT // method.addHeader("Connection", "close"); if (method.getFirstHeader("Referer") == null) { URI uri = method.getURI(); method.setHeader("Referer", uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort()); } ; try { HttpResponse resp = execute(method, httpclient); status = new HttpStatus(resp.getStatusLine()); if (resp.getEntity() != null) { status.setMessage(EntityUtils.toString(resp.getEntity(), "UTF-8")); } } catch (IOException e) { // cancel the connection when the error happen method.abort(); throw e; } finally { HttpClientUtils.abortConnection(method, httpclient); } return status; }
public void pick() throws IOException { while (true) { pickUrl = String.format( "http://web.im.baidu.com/pick?v=30&session=&source=22&type=23&flag=1&seq=%d&ack=%s&guid=%s", sequence, ack, guid); HttpGet getRequest = new HttpGet(pickUrl); HttpResponse pickRes = httpClient.execute(getRequest); String entityStr = EntityUtils.toString(pickRes.getEntity()); System.out.println("Pick result:" + entityStr); EntityUtils.consume(pickRes.getEntity()); JSONObject jsonObject = JSONObject.fromObject(entityStr); JSONObject content = jsonObject.getJSONObject("content"); if (content != null && content.get("ack") != null) { ack = (String) content.get("ack"); JSONArray fields = content.getJSONArray("fields"); JSONObject o = fields.getJSONObject(0); String fromUser = (String) o.get("from"); System.out.println("++++Message from: " + fromUser); } updateSequence(); if (sequence > 4) { break; } } }
@Test public void testUpdate() throws Exception { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/Patient/001"); 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); OperationOutcome oo = ourCtx.newXmlParser().parseResource(OperationOutcome.class, responseContent); assertEquals("OODETAILS", oo.getIssueFirstRep().getDetails().getValue()); 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()); }
@Test public void testUpdateNoResponse() throws Exception { DiagnosticReport dr = new DiagnosticReport(); dr.setId("001"); dr.addCodedDiagnosis().addCoding().setCode("AAA"); String encoded = ourCtx.newXmlParser().encodeResourceToString(dr); ourLog.info("OUT: {}", encoded); HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/001"); httpPost.setEntity( new StringEntity(encoded, ContentType.create(Constants.CT_FHIR_XML, "UTF-8"))); HttpResponse status = ourClient.execute(httpPost); try { ourLog.info(IOUtils.toString(status.getEntity().getContent())); assertEquals(200, status.getStatusLine().getStatusCode()); assertEquals( "http://localhost:" + ourPort + "/DiagnosticReport/001/_history/002", status.getFirstHeader("location").getValue()); } finally { IOUtils.closeQuietly(status.getEntity().getContent()); } }
@Override public void execute() throws Exception { int statusCode = 0, triesCount = 0; HttpResponse response = null; logger.info("Sending bulk request to elasticsearch cluster"); String entity; synchronized (bulkBuilder) { entity = bulkBuilder.toString(); bulkBuilder = new StringBuilder(); } while (statusCode != HttpStatus.SC_OK && triesCount < serversList.size()) { triesCount++; String host = serversList.get(); String url = host + "/" + BULK_ENDPOINT; HttpPost httpRequest = new HttpPost(url); httpRequest.setEntity(new StringEntity(entity)); response = httpClient.execute(httpRequest); statusCode = response.getStatusLine().getStatusCode(); logger.info("Status code from elasticsearch: " + statusCode); if (response.getEntity() != null) logger.debug( "Status message from elasticsearch: " + EntityUtils.toString(response.getEntity(), "UTF-8")); } if (statusCode != HttpStatus.SC_OK) { if (response.getEntity() != null) { throw new EventDeliveryException(EntityUtils.toString(response.getEntity(), "UTF-8")); } else { throw new EventDeliveryException("Elasticsearch status code was: " + statusCode); } } }
/** Handle the httpResponse and return the SOAP XML String. */ protected String handleResponse(final HttpResponse response, final HttpContext context) throws IOException { final HttpEntity entity = response.getEntity(); if (null == entity.getContentType() || !entity.getContentType().getValue().startsWith("application/soap+xml")) { throw new WinRMRuntimeIOException( "Error when sending request to " + getTargetURL() + "; Unexpected content-type: " + entity.getContentType()); } final InputStream is = entity.getContent(); final Writer writer = new StringWriter(); final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); try { int n; final char[] buffer = new char[1024]; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { Closeables.closeQuietly(reader); Closeables.closeQuietly(is); EntityUtils.consume(response.getEntity()); } return writer.toString(); }
public LocalDocument getDocument(LocalQuery query, boolean recurring) throws IOException { HttpResponse response; if (recurring) { response = core.post(getRecurringUrl, query.toJson()); } else { response = core.post(getUrl, query.toJson()); } if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LocalDocument ld; try { ld = new LocalDocument(EntityUtils.toString(response.getEntity())); } catch (JsonException e) { throw new IOException(e); } InternalLogger.debug("Received document with ID " + ld.getID()); currentDocument = ld; return ld; } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) { InternalLogger.debug("No document found matching query"); EntityUtils.consume(response.getEntity()); return null; } else { logUnexpected(response); return null; } }
protected JsonResponse extractJsonResponse(HttpResponse httpResponse) throws EtcdClientException { try { StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); String json = null; if (httpResponse.getEntity() != null) { try { json = EntityUtils.toString(httpResponse.getEntity()); } catch (IOException e) { throw new EtcdClientException("Error reading response", e); } } if (statusCode != 200) { if (statusCode == 400 && json != null) { // More information in JSON } else { throw new EtcdClientException( "Error response from etcd: " + statusLine.getReasonPhrase(), statusCode); } } return new JsonResponse(json, statusCode); } finally { close(httpResponse); } }
/** 扩展卡不可用时直接从网络获取图片 */ public byte[] httpGetUrlAsByte(String url) { try { int stateCode; HttpGet httpGet = new HttpGet(url); httpGet.setHeader( "Accept-Language", (Locale.getDefault().getLanguage() + "-" + Locale.getDefault().getCountry()) .toLowerCase()); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); stateCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null && stateCode == 200) { if (httpResponse.getEntity().getContentEncoding() == null || httpResponse .getEntity() .getContentEncoding() .getValue() .toLowerCase() .indexOf("gzip") < 0) { InputStream is = httpEntity.getContent(); byte[] byt = readInStream(is); return byt; } else { InputStream is = new GZIPInputStream(new ByteArrayInputStream(EntityUtils.toByteArray(httpEntity))); byte[] byt = readInStream(is); return byt; } } } catch (IOException e) { } catch (NullPointerException ex) { } return null; }
public static String postJSON(final String url, JSONObject params, final String headValue) throws Exception { HttpPost httpRequest = new HttpPost(url); if (headValue != null) { httpRequest.setHeader(CUSTOM_HEAD_NAME, headValue); } httpRequest.setHeader("Content-Type", CONTENT_TYPE); httpRequest.setEntity(new StringEntity(params.toString(), HTTP.UTF_8)); HttpResponse httpResponse; try { httpResponse = HttpManager.execute(httpRequest); } catch (SocketException e) { httpResponse = HttpManager.execute(httpRequest); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == 200) { return EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); } else if (statusCode == 302) { throw new IOException("302"); } else { String result = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); throw new ApiRequestErrorException(result); } }
@Override protected String doInBackground(String... data) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { response = httpclient.execute(new HttpGet(url)); Log.e("HTTPClient", "Path = " + url); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); } else { // Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { e.printStackTrace(); onErrorResponse(e); } catch (IOException e) { e.printStackTrace(); onErrorResponse(e); } return responseString; }
@Test public void testUpdateWithWrongResourceType() throws Exception { Patient patient = new Patient(); patient.addIdentifier().setValue("002"); HttpPut httpPost = new HttpPut("http://localhost:" + ourPort + "/DiagnosticReport/AAAAAA"); 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(400, status.getStatusLine().getStatusCode()); String expected = "<OperationOutcome xmlns=\"http://hl7.org/fhir\"><issue><severity value=\"error\"/><details value=\"Failed to parse request body as XML resource. Error was: DataFormatException at [[row,col {unknown-source}]: [1,1]]: Incorrect resource type found, expected "DiagnosticReport" but found "Patient"\"/></issue></OperationOutcome>"; assertEquals(expected, responseContent); }
public void login() throws IOException { String checkUrl = "http://web.im.baidu.com/check?callback=_nbc_.f1&v=30&time=" + guid; HttpGet getCheck = new HttpGet(checkUrl); HttpResponse res1 = httpClient.execute(getCheck); System.out.println("Check result: " + EntityUtils.toString(res1.getEntity())); EntityUtils.consume(res1.getEntity()); }
public static void createCreative(Creative creative) throws Exception { int status = 0; String jsonString = null; CloseableHttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost("https://rest.emaildirect.com/v1/Creatives?ApiKey=apikey"); List<NameValuePair> params = creative.getParams(); post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); try { jsonString = rd.lines().collect(Collectors.joining()).toString(); System.out.println("JSON ->" + jsonString); } finally { rd.close(); } } JSONObject jObj = new JSONObject(jsonString); if (status == 201) { creative.setCreativeID(jObj.getString("CreativeID")); creative.setCreativeTimestamp(jObj.getString("Created")); dbUpdate(creative); } }
private void Login(String login, String password) { HttpClient httpclient = new DefaultHttpClient(); // Prepare a request object StringBuilder url = new StringBuilder(getResources().getString(R.string.AUTHENTIFICATION_URL)); url.append("?tag=login&login="******"&password="******"connection prete", response.getStatusLine().toString()); // Get hold of the response entity if (response.getEntity() != null) { InputStream inputStream = response.getEntity().getContent(); // Lecture du retour au format JSON BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder stringBuilder = new StringBuilder(); String ligneLue = bufferedReader.readLine(); while (ligneLue != null) { stringBuilder.append(ligneLue + " \n"); ligneLue = bufferedReader.readLine(); } bufferedReader.close(); // Get hold of the response entity JSONObject jsonObject = new JSONObject(stringBuilder.toString()); Log.i("Chaine JSON", stringBuilder.toString()); // JSONObject jsonResultSet = jsonObject.getJSONObject("nb"); jsonObject.getJSONObject("utilisateurs").getString("mail"); jsonObject.get("id"); if (jsonObject.getBoolean("error") == false) { Intent i = new Intent(getApplicationContext(), LoggedActivity.class); startActivity(i); } else { Toast.makeText(getApplicationContext(), "Erreur d'identification", Toast.LENGTH_LONG) .show(); } // If the response does not enclose an entity, there is no need // to worry about connection release } } catch (Exception e) { e.printStackTrace(); } }
// function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if (method == "POST") { // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; }
@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); }
protected String convertResponseToString(HttpResponse response, boolean pIgnoreStatus) throws IOException { int statuscode = response.getStatusLine().getStatusCode(); if (statuscode != 200 && statuscode != 201 && !pIgnoreStatus) { throw new ParseException( "server respond with " + response.getStatusLine().getStatusCode() + ": " + EntityUtils.toString(response.getEntity()) + response.getStatusLine().getStatusCode() + ": <unparsable body>"); } HttpEntity entity = response.getEntity(); if (entity == null) { throw new ParseException("http body was empty"); } long len = entity.getContentLength(); if (len > 2048) { throw new ParseException( "http body is to big and must be streamed (max is 2048, but was " + len + " byte)"); } String body = EntityUtils.toString(entity, HTTP.UTF_8); return body; }
@Test public void testServerReturnsAnHttp401() throws Exception { ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class); when(myHttpResponse.getStatusLine()) .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 401, "Unauthorized")); when(myHttpResponse.getEntity().getContentType()) .thenReturn(new BasicHeader("content-type", Constants.CT_TEXT)); when(myHttpResponse.getEntity().getContent()) .thenAnswer( new Answer<InputStream>() { @Override public InputStream answer(InvocationOnMock theInvocation) throws Throwable { return new ReaderInputStream( new StringReader("Unauthorized"), Charset.forName("UTF-8")); } }); when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse); IGenericClient client = myCtx.newRestfulGenericClient("http://foo"); try { client.read().resource(Patient.class).withId("123").execute(); fail(); } catch (AuthenticationException e) { // good } }
private void saveSong(String songTitle, String songUrl) throws IOException, ClientProtocolException, FileNotFoundException { HttpGet get = new HttpGet(songUrl); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); File SDCardRoot = Environment.getExternalStorageDirectory(); File file = new File(SDCardRoot, "/music/" + songTitle + ".mp3"); if (!file.exists()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = response.getEntity().getContent(); long totalSize = response.getEntity().getContentLength(); long downloadedSize = 0; // send message sendMsg(0, totalSize, downloadedSize, songTitle); byte[] buffer = new byte[1024]; int bufferLength = 0; // used to store a temporary size of the buffer while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; sendMsg(1, totalSize, downloadedSize, songTitle); } fileOutput.close(); sendMsg(2, totalSize, downloadedSize, songTitle); }
public byte[] handleResponse(HttpResponse hr) throws ClientProtocolException, IOException { if (hr.getStatusLine().getStatusCode() == 200) { if (hr.getEntity().getContentEncoding() == null) { return EntityUtils.toByteArray(hr.getEntity()); } if (hr.getEntity().getContentEncoding().getValue().contains("gzip")) { GZIPInputStream gis = null; try { gis = new GZIPInputStream(hr.getEntity().getContent()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = gis.read(b)) != -1) baos.write(b, 0, n); System.out.println("Gzipped"); return baos.toByteArray(); } catch (IOException e) { throw e; } finally { try { if (gis != null) gis.close(); } catch (IOException ex) { throw ex; } } } return EntityUtils.toByteArray(hr.getEntity()); } if (hr.getStatusLine().getStatusCode() == 302) { throw new IOException("302"); } return null; }
public ArrayList<University> getUniversityList(String UNIVERSITY_LIST) throws Exception { ArrayList<University> unis = new ArrayList<University>(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(UNIVERSITY_LIST); HttpResponse httpResponse = httpClient.execute(httpGet); httpResponse.setEntity(httpResponse.getEntity()); HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { InputStream inputStream = httpEntity.getContent(); String jsonFile = convertStreamToString(inputStream); JSONArray json = new JSONArray(jsonFile); for (int i = 0; i < json.length(); ++i) { JSONObject uni = (JSONObject) json.get(i); University unio = new University(); // Add 10 to id to prevent collision with Australian University // Id's unio.setId(10 + Integer.parseInt(uni.getString("id"))); unio.setName(uni.getString("name")); unio.setAbbrName(uni.getString("abbr_name")); unio.setImgUrl(uni.getString("logo")); unis.add(unio); } } return unis; }
@Override protected String doInBackground(String... uri) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { response = httpclient.execute(new HttpGet(uri[0])); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); } else { // Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { // TODO Handle problems.. } catch (IOException e) { // TODO Handle problems.. } return responseString; }
@Test public void testBasicAuthenticationCredentialsCaching() throws Exception { this.localServer.register("*", new AuthHandler()); this.localServer.start(); BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("test", "test")); TestTargetAuthenticationStrategy authStrategy = new TestTargetAuthenticationStrategy(); this.httpclient.setCredentialsProvider(credsProvider); this.httpclient.setTargetAuthenticationStrategy(authStrategy); HttpContext context = new BasicHttpContext(); HttpHost targethost = getServerHttp(); HttpGet httpget = new HttpGet("/"); HttpResponse response1 = this.httpclient.execute(targethost, httpget, context); HttpEntity entity1 = response1.getEntity(); Assert.assertEquals(HttpStatus.SC_OK, response1.getStatusLine().getStatusCode()); Assert.assertNotNull(entity1); EntityUtils.consume(entity1); HttpResponse response2 = this.httpclient.execute(targethost, httpget, context); HttpEntity entity2 = response1.getEntity(); Assert.assertEquals(HttpStatus.SC_OK, response2.getStatusLine().getStatusCode()); Assert.assertNotNull(entity2); EntityUtils.consume(entity2); Assert.assertEquals(1, authStrategy.getCount()); }