@Override @Test public void testRepresentation() throws Exception { GetMethod getMethod = executeGet( getUriBuilder(PageResource.class).build(getWiki(), "Main", "WebHome").toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Page page = (Page) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Link link = getFirstLinkByRelation(page, Relations.OBJECTS); Assert.assertNotNull(link); getMethod = executeGet(link.getHref()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Objects objects = (Objects) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertFalse(objects.getObjectSummaries().isEmpty()); for (ObjectSummary objectSummary : objects.getObjectSummaries()) { link = getFirstLinkByRelation(objectSummary, Relations.OBJECT); getMethod = executeGet(link.getHref()); Assert.assertEquals( getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Object object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); checkLinks(objectSummary); for (Property property : object.getProperties()) { checkLinks(property); } } }
@Test public void testPUTObjectUnauthorized() throws Exception { final String TAG_VALUE = UUID.randomUUID().toString(); Object objectToBePut = getObject("XWiki.TagClass"); GetMethod getMethod = executeGet( getUriBuilder(ObjectResource.class) .build( getWiki(), "Main", "WebHome", objectToBePut.getClassName(), objectToBePut.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Object object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); String originalTagValue = getProperty(object, "tags").getValue(); getProperty(object, "tags").setValue(TAG_VALUE); PutMethod putMethod = executePutXml( getUriBuilder(ObjectResource.class) .build( getWiki(), "Main", "WebHome", objectToBePut.getClassName(), objectToBePut.getNumber()) .toString(), object); Assert.assertEquals( getHttpMethodInfo(putMethod), HttpStatus.SC_UNAUTHORIZED, putMethod.getStatusCode()); getMethod = executeGet( getUriBuilder(ObjectResource.class) .build( getWiki(), "Main", "WebHome", objectToBePut.getClassName(), objectToBePut.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertEquals(originalTagValue, getProperty(object, "tags").getValue()); }
public String getURL(String url, String username, String pw) throws MalformedURLException { GetMethod httpMethod = null; try { HttpClient client = new HttpClient(); setAuth(client, url, username, pw); httpMethod = new GetMethod(url); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(httpMethod); if (status == HttpStatus.SC_OK) { InputStream is = httpMethod.getResponseBodyAsStream(); String response = IOUtils.toString(is); if (response.trim().length() == 0) { // sometime gs rest fails logger.warn("ResponseBody is empty"); return null; } else { return response; } } else { logger.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url); } } catch (ConnectException e) { logger.info("Couldn't connect to [" + url + "]"); } catch (IOException e) { logger.info("Error talking to [" + url + "]", e); } finally { if (httpMethod != null) httpMethod.releaseConnection(); } return null; }
public static Bitmap readImg(String id) { String uri = "http://" + PostUrl.Media + ":8080/upload/" + id + ".jpg"; HttpClient client = new HttpClient(); client.getParams().setContentCharset("utf-8"); client.getParams().setSoTimeout(10000); client .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); GetMethod getMethod = new GetMethod(uri); System.out.println("1"); try { if (client.executeMethod(getMethod) == HttpStatus.SC_OK) { System.out.println("2"); InputStream inputStream = getMethod.getResponseBodyAsStream(); System.out.println("3"); Bitmap img = BitmapFactory.decodeStream(inputStream); inputStream.close(); return img; } } catch (HttpException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { getMethod.releaseConnection(); } System.out.println("图片下载不了"); return null; }
private String getRequest(String path) { logger.log(Level.FINEST, "PR-GET-REQUEST:" + path); HttpClient client = getHttpClient(); client.getState().setCredentials(AuthScope.ANY, credentials); GetMethod httpget = new GetMethod(path); client.getParams().setAuthenticationPreemptive(true); String response = null; int responseCode; try { responseCode = client.executeMethod(httpget); InputStream responseBodyAsStream = httpget.getResponseBodyAsStream(); StringWriter stringWriter = new StringWriter(); IOUtils.copy(responseBodyAsStream, stringWriter, "UTF-8"); response = stringWriter.toString(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Failed to process PR get request; " + path, e); } logger.log(Level.FINEST, "PR-GET-RESPONSE:" + response); if (!validResponseCode(responseCode)) { logger.log(Level.SEVERE, "Failing to get response from Stash PR GET" + path); throw new RuntimeException( "Didn't get a 200 response from Stash PR GET! Response; '" + HttpStatus.getStatusText(responseCode) + "' with message; " + response); } return response; }
@Override public void download(String url, OutputStream output) { Cookie cookie = new Cookie(".dmm.co.jp", SESSION_ID_KEY, sessionId, "/", null, false); HttpClient client = new HttpClient(); client.getState().addCookie(cookie); GetMethod method = new GetMethod(url); try { downloding.set(true); client.executeMethod(method); InputStream input = method.getResponseBodyAsStream(); try { IOUtils.copyLarge(input, output); byte[] buffer = new byte[4096]; int n = 0; while (downloding.get() && -1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } if (!downloding.get()) { LOGGER.warn("interrupted to download " + url); } } finally { IOUtils.closeQuietly(input); } } catch (IOException e) { throw new EgetException("failed to download " + url, e); } finally { downloding.set(false); method.releaseConnection(); } }
@Test public void testPOSTObjectFormUrlEncoded() throws Exception { final String TAG_VALUE = "TAG"; NameValuePair[] nameValuePairs = new NameValuePair[2]; nameValuePairs[0] = new NameValuePair("className", "XWiki.TagClass"); nameValuePairs[1] = new NameValuePair("property#tags", TAG_VALUE); PostMethod postMethod = executePostForm( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), nameValuePairs, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); Object object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); GetMethod getMethod = executeGet( getUriBuilder(ObjectResource.class) .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); }
@Test public void testPOSTObject() throws Exception { final String TAG_VALUE = "TAG"; Property property = new Property(); property.setName("tags"); property.setValue(TAG_VALUE); Object object = objectFactory.createObject(); object.setClassName("XWiki.TagClass"); object.getProperties().add(property); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); GetMethod getMethod = executeGet( getUriBuilder(ObjectResource.class) .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); }
/** * Send the command to Solr using a GET * * @param queryString * @param url * @return * @throws IOException */ private static String sendGetCommand(String queryString, String url) throws IOException { String results = null; HttpClient client = new HttpClient(); GetMethod get = new GetMethod(url); get.setQueryString(queryString.trim()); client.executeMethod(get); try { // Execute the method. int statusCode = client.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + get.getStatusLine()); results = "Method failed: " + get.getStatusLine(); } results = getStringFromStream(get.getResponseBodyAsStream()); } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. get.releaseConnection(); } return results; }
protected void loadNetImage() { String url = "http://ww2.sinaimg.cn/thumbnail/675e5a2bjw1e0pydwgwgnj.jpg"; HttpClient httpClient = null; GetMethod httpGet = null; Bitmap bitmap = null; try { httpClient = getHttpClient(); httpGet = getHttpGet(url, null, null); if (httpClient.executeMethod(httpGet) == HttpStatus.SC_OK) { InputStream inStream = httpGet.getResponseBodyAsStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); mImageView03.setImageBitmap(bitmap); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpGet.releaseConnection(); httpClient = null; } }
public InputStream getAttachment( String wikiName, String spaceName, String pageName, String attachmentName) { HttpClient httpClient = restResource.getClient(); String uri = String.format( "%s/wikis/%s/spaces/%s/pages/%s/attachments/%s", DefaultRestResource.REST_URI, wikiName, spaceName, pageName, attachmentName); GetMethod getMethod = new GetMethod(uri); getMethod.addRequestHeader("Accept", "application/xml"); getMethod.addRequestHeader("Accept-Ranges", "bytes"); try { httpClient.executeMethod(getMethod); return getMethod.getResponseBodyAsStream(); } catch (HttpException e) { String message = String.format( "Unable to process GET request for the attachment '%s:%s.%s@%s'.", wikiName, spaceName, pageName, attachmentName); logger.error(message, e); return null; } catch (IOException e) { String message = String.format( "Unable to GET the attachment '%s:%s.%s@%s'.", wikiName, spaceName, pageName, attachmentName); logger.error(message, e); return null; } }
public List<DatastreamProfile> getDatastreamHistory(String pid, String dsId) throws HttpException, IOException, FedoraException, SAXException, ParserConfigurationException, XPathExpressionException { String url = this.fedoraBaseUrl + "/objects/" + pid + "/datastreams/" + dsId + "/history?format=xml"; GetMethod get = new GetMethod(url); this.client.executeMethod(get); if (get.getStatusCode() == 200) { List<DatastreamProfile> history = new ArrayList<DatastreamProfile>(); Document xml = this.getDocumentBuilder().parse(get.getResponseBodyAsStream()); NodeList nl = (NodeList) this.getXPath() .evaluate( "/fedora-management:datastreamHistory/fedora-management:datastreamProfile", xml, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Element el = (Element) nl.item(i); history.add(new DatastreamProfile(this, el)); } return history; } else { throw new FedoraException("REST action \"" + url + "\" failed: " + get.getStatusLine()); } }
/** * Fetches the object profile XML and parse out the property value for the given property. * * @param pid the pid of the object to be queried * @param dsName the name of the datastream who's property is being queried * @param prop the property to query. * @return the value of the property */ public String getDatastreamProperty( String pid, String dsName, DatastreamProfile.DatastreamProperty prop) throws HttpException, IOException, SAXException, ParserConfigurationException, FedoraException, XPathExpressionException { String url = this.fedoraBaseUrl + "/objects/" + pid + "/datastreams/" + dsName + "?format=xml"; GetMethod get = new GetMethod(url); this.client.executeMethod(get); if (get.getStatusCode() == 200) { Document xml = this.getDocumentBuilder().parse(get.getResponseBodyAsStream()); // compatible with fedora 3.4 String value = (String) this.getXPath() .evaluate( "/fedora-management:datastreamProfile/fedora-management:" + prop.getPropertyName(), xml, XPathConstants.STRING); if (value != null) { return value; } else { // compatible with fedora 3.2 return (String) this.getXPath() .evaluate( "/datastreamProfile/" + prop.getPropertyName(), xml, XPathConstants.STRING); } } else { throw new FedoraException("REST action \"" + url + "\" failed: " + get.getStatusLine()); } }
public Object execute(Map properties) { WorkflowAssignment wfAssignment = (WorkflowAssignment) properties.get("workflowAssignment"); String jsonUrl = (String) properties.get("jsonUrl"); GetMethod get = null; try { HttpClient client = new HttpClient(); jsonUrl = WorkflowUtil.processVariable(jsonUrl, "", wfAssignment); jsonUrl = StringUtil.encodeUrlParam(jsonUrl); get = new GetMethod(jsonUrl); client.executeMethod(get); InputStream in = get.getResponseBodyAsStream(); String jsonResponse = streamToString(in); Map object = PropertyUtil.getPropertiesValueFromJson(jsonResponse); storeToForm(wfAssignment, properties, object); storeToWorkflowVariable(wfAssignment, properties, object); } catch (Exception ex) { LogUtil.error(getClass().getName(), ex, ""); } finally { if (get != null) { get.releaseConnection(); } } return null; }
public DatastreamProfile getDatastream(String pid, String dsId) throws IOException { DatastreamProfile result = null; try { StringBuilder uri = new StringBuilder(getBaseUrl()); uri.append("/objects/"); uri.append(pid); uri.append("/datastreams/"); uri.append(dsId); uri.append(".xml"); GetMethod method = new GetMethod(uri.toString()); int status = executeMethod(method, true); if (status == 200) { JAXBContext jc = JAXBContext.newInstance(DatastreamProfile.class); Unmarshaller um = jc.createUnmarshaller(); InputStream in = method.getResponseBodyAsStream(); result = (DatastreamProfile) um.unmarshal(in); in.close(); } method.releaseConnection(); } catch (JAXBException jaxbe) { log.error("Failed parsing result", jaxbe); } return result; }
/** AKA scraping */ public TorrentStatus getStatus() throws IOException { if (!isGetStatusSupported()) { throw new IllegalStateException("Get status (scraping) not supported on this tracker"); } String path = announceUrl.getFile(); int i = path.lastIndexOf('/'); path = path.substring(0, i + 1) + "scrape" + path.substring(i + ANNOUNCE.length() + 1); GetMethod method = new GetMethod(path); method.setRequestHeader("User-Agent", "BlackBits/0.1"); StringBuffer queryString = new StringBuffer(announceUrl.getQuery() == null ? "" : announceUrl.getQuery()); queryString.append("info_hash=" + URLUtils.encode(infoHash.getBytes())); method.setQueryString(queryString.toString()); httpClient.executeMethod(method); BDecoder decoder = new BDecoder(method.getResponseBodyAsStream()); BDictionary dictionary = (BDictionary) decoder.decodeNext(); BDictionary files = (BDictionary) dictionary.get("files"); String key = (String) files.keySet().iterator().next(); BDictionary info = (BDictionary) files.get(key); BLong seeders = (BLong) info.get("complete"); BLong leechers = (BLong) info.get("incomplete"); BLong numberOfDownloads = (BLong) info.get("downloaded"); return new TorrentStatus(seeders.intValue(), leechers.intValue(), numberOfDownloads.intValue()); }
public PidListType getNextPid(int numPids, String namespace) throws IOException { PidListType result = null; try { StringBuilder uri = new StringBuilder(getBaseUrl()); uri.append("/objects/nextPID?numPIDs="); uri.append(numPids); if (namespace != null) { uri.append("&namespace="); uri.append(namespace); } uri.append("&format=xml"); GetMethod method = new GetMethod(uri.toString()); int status = executeMethod(method); if (status == HttpStatus.SC_OK) { JAXBContext jc = JAXBContext.newInstance(PidListType.class); Unmarshaller um = jc.createUnmarshaller(); InputStream in = method.getResponseBodyAsStream(); result = (PidListType) um.unmarshal(in); in.close(); } method.releaseConnection(); } catch (JAXBException jaxbe) { log.error("Failed parsing result", jaxbe); } return result; }
private TrackerResponse decodeResponse(GetMethod method) throws IOException, TrackerCommunicationException { BDecoder decoder = new BDecoder(method.getResponseBodyAsStream()); BDictionary dictionary = (BDictionary) decoder.decodeNext(); if (dictionary.get("failure reason") != null) { BString failureReason = (BString) dictionary.get("failure reason"); throw new TrackerCommunicationException(failureReason.getStringValue()); } int seeders = getInt(dictionary, "complete"); int leechers = getInt(dictionary, "incomplete"); int updateInterval = getInt(dictionary, "interval"); BList peersList = (BList) dictionary.get("peers"); List peers = new ArrayList(); for (Iterator i = peersList.iterator(); i.hasNext(); ) { BDictionary peerDictionary = (BDictionary) i.next(); peers.add( new Peer( ((BString) peerDictionary.get("peer id")).getStringValue(), ((BLong) peerDictionary.get("port")).intValue(), ((BString) peerDictionary.get("ip")).getStringValue())); } return new TrackerResponse(seeders, leechers, updateInterval, peers); }
@Test public void testGetXmlAndValidateXmlSchema() throws IOException, ParserConfigurationException, SAXException { HttpClient httpClient = new HttpClient(); GetMethod get = new GetMethod("http://localhost/ch13personal/personal.xml"); Document document; try { httpClient.executeMethod(get); InputStream input = get.getResponseBodyAsStream(); // Parse the XML document into a DOM tree DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); document = parser.parse(input); } finally { get.releaseConnection(); } // Create a SchemaFactory capable of understanding WXS schemas SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); // load a WXS schema, represented by a Schema instance Source schemaFile = new StreamSource(new File("src/main/webapp/personal.xsd")); Schema schema = factory.newSchema(schemaFile); // create a Validator instance, which can be used to validate an // instance document Validator validator = schema.newValidator(); // validate the DOM tree validator.validate(new DOMSource(document)); }
public static boolean downloadFile(String url, String filePath) { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.error("downloadFile fail.url={},status={}", url, statusCode); return false; } BufferedInputStream bis = new BufferedInputStream(method.getResponseBodyAsStream()); FileOutputStream fos = new FileOutputStream(new File(filePath)); BufferedOutputStream bos = new BufferedOutputStream(fos); int len; while ((len = bis.read()) != -1) { bos.write(len); } bos.flush(); bos.close(); fos.close(); bis.close(); return true; } catch (Exception e) { logger.error("url=" + url, e); return false; } finally { method.releaseConnection(); } }
@Override @Before public void setUp() throws Exception { super.setUp(); GetMethod getMethod = executeGet( getUriBuilder(PageResource.class).build(getWiki(), "Main", "WebHome").toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Page page = (Page) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Link link = getFirstLinkByRelation(page, Relations.OBJECTS); /* Create a tag object if it doesn't exist yet */ if (link == null) { Object object = objectFactory.createObject(); object.setClassName("XWiki.TagClass"); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); } }
public static boolean getURLContent(final String url, final StringBuffer content) throws MalformedURLException, IOException { HttpClient httpClient = HttpUtil.getClient(); try { GetMethod call = new GetMethod(url); int status = httpClient.executeMethod(call); if (status == 200) { InputStream response = call.getResponseBodyAsStream(); try { byte[] buffer = new byte[2048]; int size = response.read(buffer); while (size > 0) { for (int idx = 0; idx < size; idx++) { content.append((char) buffer[idx]); } size = response.read(buffer); } } catch (Exception e) { // we can ignore this because the content comparison will fail } } } catch (Throwable e) { StringWriter writer = new StringWriter(); PrintWriter writer2 = new PrintWriter(writer); e.printStackTrace(writer2); content.append(writer.getBuffer()); return false; } return true; }
/** * Checks whether the object with the given PID has a datastream with the given identifier * (dsName). * * @param pid the fedora persistent identifier for the object whose datastreams are being queried * @param dsName the identifier for the datastream * @return true if the datastream exists, false otherwise * @throws IOException if an error occurs while accessing fedora * @throws FedoraException */ public boolean hasDatastream(String pid, String dsName) throws IOException, FedoraException { GetMethod get = new GetMethod(this.fedoraBaseUrl + "/objects/" + pid + "/datastreams?format=xml"); this.client.executeMethod(get); return (readStream(get.getResponseBodyAsStream(), get.getResponseCharSet()) .indexOf("dsid=\"" + dsName + "\"") != -1); }
private String fetchPatchContentFromUrl(final String url) throws IOException { GetMethod m = new GetMethod(url); getHttpClient().executeMethod(m); if (m.getStatusCode() == HttpStatus.SC_OK) { return IOUtilities.toString(m.getResponseBodyAsStream()); } return null; }
/** * Retrieves the build number of this CloudTest server. Postcondition: The build number returned * is never null. */ public VersionNumber getBuildNumber() throws IOException { if (url == null) { // User didn't enter a value in the Configure Jenkins page. // Nothing we can do. throw new IllegalStateException("No URL has been configured for this CloudTest server."); } final String[] v = new String[1]; try { HttpClient hc = createClient(); GetMethod get = new GetMethod(url); hc.executeMethod(get); if (get.getStatusCode() != 200) { throw new IOException(get.getStatusLine().toString()); } SAXParser sp = SAXParserFactory.newInstance().newSAXParser(); sp.parse( get.getResponseBodyAsStream(), new DefaultHandler() { @Override public InputSource resolveEntity(String publicId, String systemId) throws IOException, SAXException { if (systemId.endsWith(".dtd")) return new InputSource(new StringReader("")); return null; } @Override public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equals("meta")) { if ("buildnumber".equals(attributes.getValue("name"))) { v[0] = attributes.getValue("content"); throw new SAXException("found"); } } } }); LOGGER.warning("Build number not found in " + url); } catch (SAXException e) { if (v[0] != null) return new VersionNumber(v[0]); LOGGER.log(Level.WARNING, "Failed to load " + url, e); } catch (ParserConfigurationException e) { throw new Error(e); } // If we reach this point, then we failed to extract the build number. throw new IOException( "Failed to extract build number from \'" + this.getDescriptor().getDisplayName() + "\': <" + url + ">."); }
/** * 获取网络图片 * * @param url * @return */ public static Bitmap getBitmapByNet(String url) throws AppException { // System.out.println("image_url==> "+url); URI uri = null; try { uri = new URI(url, false, "UTF-8"); } catch (URIException e) { e.printStackTrace(); } if (uri != null) url = uri.toString(); HttpClient httpClient = null; GetMethod httpGet = null; Bitmap bitmap = null; int time = 0; do { try { httpClient = HttpHelper.getHttpClient(); httpGet = HttpHelper.getHttpGet(url, HttpHelper.getUserAgent()); int statusCode = httpClient.executeMethod(httpGet); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } InputStream inStream = httpGet.getResponseBodyAsStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生网络异常 e.printStackTrace(); throw AppException.network(e); } finally { // 释放连接 httpGet.releaseConnection(); } } while (time < RETRY_TIME); return bitmap; }
/* * Tests the <tt>withBody(byte[])</tt> method. The byte array is used straight as the response body * and then retrieved. */ @Test public void withBodyArrayOfBytes() throws IOException { onRequest().respond().withBody(BINARY_BODY); final GetMethod method = new GetMethod("http://localhost:" + port()); client.executeMethod(method); final byte[] resultBody = IOUtils.toByteArray(method.getResponseBodyAsStream()); assertThat(resultBody, is(BINARY_BODY)); }
private String sendRequest(TicketsRequest request) throws HttpException, IOException { String html = ""; GetMethod get = new GetMethod(url2); client.executeMethod(get); int statusCodeInit = client.executeMethod(get); if (statusCodeInit != HttpStatus.SC_OK) { logger.error("sendRequest method failed. Get method failed: " + get.getStatusLine()); return null; } else { html = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"); } parseToken(html); client.getHttpConnectionManager().getParams().setSoTimeout(10000); PostMethod post = new PostMethod(URL); post.addRequestHeader("Accept", "*/*"); post.addRequestHeader("Accept-Encoding", "gzip, deflate"); post.addRequestHeader("Accept-Language", "uk,ru;q=0.8,en-US;q=0.5,en;q=0.3"); // post.addRequestHeader("Cache-Control", "no-cache"); post.addRequestHeader("Connection", "keep-alive"); // post.addRequestHeader("Content-Length", "288"); //202. 196 post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); post.addRequestHeader("GV-Ajax", "1"); post.addRequestHeader("GV-Referer", "http://booking.uz.gov.ua/"); post.addRequestHeader("GV-Screen", "1920x1080"); post.addRequestHeader("GV-Token", token); post.addRequestHeader("GV-Unique-Host", "1"); post.addRequestHeader("Host", "booking.uz.gov.ua"); // post.addRequestHeader("Pragma", "no-cache"); post.addRequestHeader("Origin", "http://booking.uz.gov.ua"); post.addRequestHeader("Referer", "http://booking.uz.gov.ua/"); post.addRequestHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/39.0"); post.addParameter("another_ec", "0"); post.addParameter("date_dep", new SimpleDateFormat("dd.MM.yyyy").format(request.date)); post.addParameter("search", ""); post.addParameter("station_from", request.from.getName()); post.addParameter("station_id_from", request.from.getStationId()); post.addParameter("station_id_till", request.till.getStationId()); post.addParameter("station_till", request.till.getName()); post.addParameter("time_dep", "00:00"); post.addParameter("time_dep_till", ""); int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { logger.error("sendRequest method failed. Post method failed: " + post.getStatusLine()); return null; } return post.getResponseBodyAsString(); }
private T requestInfo(URI baseUrl, RenderingContext context) throws IOException, URISyntaxException, ParserConfigurationException, SAXException { URL url = loader.createURL(baseUrl, context); GetMethod method = null; try { final InputStream stream; if ((url.getProtocol().equals("http") || url.getProtocol().equals("https")) && context.getConfig().localHostForwardIsFrom(url.getHost())) { String scheme = url.getProtocol(); final String host = url.getHost(); if (url.getProtocol().equals("https") && context.getConfig().localHostForwardIsHttps2http()) { scheme = "http"; } URL localUrl = new URL(scheme, "localhost", url.getPort(), url.getFile()); HttpURLConnection connexion = (HttpURLConnection) localUrl.openConnection(); connexion.setRequestProperty("Host", host); for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) { connexion.setRequestProperty(entry.getKey(), entry.getValue()); } stream = connexion.getInputStream(); } else { method = new GetMethod(url.toString()); for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) { method.setRequestHeader(entry.getKey(), entry.getValue()); } context.getConfig().getHttpClient(baseUrl).executeMethod(method); int code = method.getStatusCode(); if (code < 200 || code >= 300) { throw new IOException( "Error " + code + " while reading the Capabilities from " + url + ": " + method.getStatusText()); } stream = method.getResponseBodyAsStream(); } final T result; try { result = loader.parseInfo(stream); } finally { stream.close(); } return result; } finally { if (method != null) { method.releaseConnection(); } } }
/** use httpclient to get the data */ public static ByteBuffer getDataFromURI(String uri) throws IOException { GetMethod get = new GetMethod(uri); try { new HttpClient().executeMethod(get); return new ByteBuffer(get.getResponseBodyAsStream()); } finally { get.releaseConnection(); } }