@Override public Object getResponseContent(HttpURLConnection conn) throws IOException, ClientException { Exception error = null; InputStream input; if (conn == null) { throw new ClientException("Network error", null); } try { input = conn.getInputStream(); } catch (Exception e) { Log.w("AndroidClient", e.toString()); error = e; input = conn.getErrorStream(); } Map<String, List<String>> headerFields = conn.getHeaderFields(); if (headerFields != null) { Log.i("Base", headerFields.toString()); } if (input != null) { Log.i("Base", "class " + input.getClass().getName()); } final int responseCode = conn.getResponseCode(); if (responseCode == 404) throw new ClientException("Item not found", null); if (input != null && input.getClass().getName().startsWith("libcore.net.http.HttpResponseCache")) { input = new GZIPInputStream(input); } final StringBuilder builder = new StringBuilder(); if (input != null) { final BufferedReader br = new BufferedReader(new InputStreamReader(input)); try { String output; while ((output = br.readLine()) != null) builder.append(output); } finally { br.close(); } } conn.disconnect(); if (responseCode >= 300 || error != null) throw new ClientException( responseCode, (error != null ? error.getMessage() : "") + ", response: " + builder, error); if (builder.length() == 0) return null; try { if (conn.getContentType().contains(JSON_MIME_TYPE)) return new JSONObject(builder.toString()); } catch (JSONException e) { throw new ClientException(e); } return builder.toString(); }
/** * Discover the content length and content type for an enclosure URL * * @param rssEnclosureURL URL for enclosure * @return String array containing the enclosure's content length and content type */ protected String[] discoverEnclosureProperties(String rssEnclosureURL) { String[] enclosureProperties = new String[] {"", ""}; try { if (!rssEnclosureURL.toLowerCase().startsWith("http://")) { if (_logger.isDebugEnabled()) { _logger.debug("RSS enclosure URL not an HTTP-accessible resource"); } } else { URL enclosure = new URL(rssEnclosureURL); HttpURLConnection httpURLConnection = (HttpURLConnection) enclosure.openConnection(); httpURLConnection.setRequestMethod("HEAD"); httpURLConnection.connect(); enclosureProperties[0] = Integer.toString(httpURLConnection.getContentLength()); enclosureProperties[1] = httpURLConnection.getContentType(); httpURLConnection.disconnect(); } } catch (Exception e) { if (_logger.isErrorEnabled()) { _logger.error("Error retrieving enclosure properties", e); } } return enclosureProperties; }
/** * Fetch the provided URI, returning a {@link JarInputStream} if the response body is appropriate. * * <p>Protected to allow for mocking. * * @return the entity body as a stream, or null on failure. */ @SuppressWarnings("static-method") @RobocopTarget protected JarInputStream fetchDistribution(URI uri, HttpURLConnection connection) throws IOException { final int status = connection.getResponseCode(); Log.d(LOGTAG, "Distribution fetch: " + status); // We record HTTP statuses as 2xx, 3xx, 4xx, 5xx => 2, 3, 4, 5. final int value; if (status > 599 || status < 100) { Log.wtf(LOGTAG, "Unexpected HTTP status code: " + status); value = CODE_CATEGORY_STATUS_OUT_OF_RANGE; } else { value = status / 100; } Telemetry.addToHistogram(HISTOGRAM_CODE_CATEGORY, value); if (status != 200) { Log.w(LOGTAG, "Got status " + status + " fetching distribution."); Telemetry.addToHistogram(HISTOGRAM_CODE_CATEGORY, CODE_CATEGORY_FETCH_NON_SUCCESS_RESPONSE); return null; } final String contentType = connection.getContentType(); if (contentType == null || !contentType.startsWith(EXPECTED_CONTENT_TYPE)) { Log.w(LOGTAG, "Malformed response: invalid Content-Type."); Telemetry.addToHistogram(HISTOGRAM_CODE_CATEGORY, CODE_CATEGORY_FETCH_INVALID_CONTENT_TYPE); return null; } return new JarInputStream(new BufferedInputStream(connection.getInputStream()), true); }
public static String post(String url, byte[] body, String contentType) throws IOException { try { HttpURLConnection conn = openConnection(url); conn.setRequestMethod("POST"); conn.setDoOutput(true); if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } conn.getOutputStream().write(body); if (conn.getResponseCode() != 200) { logger.error( "response error {},request {}", IOUtils.toString(conn.getErrorStream()), new String(body)); return ""; } contentType = conn.getContentType(); String encoding = "utf-8"; if (contentType != null && contentType.indexOf("charset=") > 0) { encoding = contentType.split("charset=")[1]; } InputStream is = conn.getInputStream(); byte[] resp = IOUtils.toByteArray(is); conn.disconnect(); return new String(resp, encoding); } catch (MalformedURLException | URISyntaxException e) { logger.error("", e); return ""; } }
/** * This method will test the return type to make sure that it is between 200 (inclusive) and 300 * (exclusive), i.e. that it is "successful". If it is not then it will throw an {@link * RequestFailureException} with the response code and message from the error stream. * * @param connection * @throws RequestFailureException * @throws IOException * @see HttpURLConnection#getResponseCode() * @see HttpURLConnection#getErrorStream() */ private void testResponseCode(HttpURLConnection connection) throws RequestFailureException, IOException { int responseCode = connection.getResponseCode(); if (responseCode < 200 || responseCode >= 300) { // Not one of the OK response codes so get the message off the error stream and throw an // exception InputStream errorStream = connection.getErrorStream(); String errorStreamString = null; String message = null; if (errorStream != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int read = -1; while ((read = errorStream.read()) != -1) { outputStream.write(read); } errorStreamString = outputStream.toString(getCharset(connection.getContentType())); // The content of the error stream coming from Massive seems to vary in structure (HTML, // JSON) see if it is is JSON and get a good message or use it as is message = parseErrorObject(errorStreamString); } throw new RequestFailureException( responseCode, message, connection.getURL(), errorStreamString); } }
@Test public void changeBodyTest() throws Exception { HttpURLConnection httpCon = getConnection( "http://localhost:8080/test/application/api?__type=14&__moduleName=TestHttpContext&__methodName=changeBody"); checkResponceCode(httpCon); assertEquals(httpCon.getContentLength(), 683); String type = httpCon.getContentType(); String charset = ""; String[] values = type.split(";"); for (String value : values) { if (value.toLowerCase().startsWith("charset=")) { charset = value.substring("charset=".length()); } } charset = charset.isEmpty() ? "utf-8" : charset; String text = new String( BinaryUtils.readStream(httpCon.getInputStream(), httpCon.getContentLength()), charset); assertEquals( text, "Фишер: \"В 1970 году в Бледе я принял участие в международном \n" + "блицтурнире. В партии с Петросяном мы то и дело обменивались шахами, причем он произносил \n" + "это слово по-русски, а я – по-английски. В момент, когда у обоих уже начали зависать флажки,\n" + "я вдруг сказал по-русски: \"Вам шах, гроссмейстер!\" Петросян настолько поразился, что на какой-то \n" + "момент забыл о флажке и просрочил время."); }
@Test @RunAsClient public void testUpdateAssetFromAtomWithStateNotExist(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL + "rest/packages/restPackage1/assets/model1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); InputStream in = connection.getInputStream(); assertNotNull(in); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); // Update state ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA); ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE); stateExtension.<Element>getExtension(Translator.VALUE).setText("NonExistState"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("PUT"); connection.setRequestProperty("Content-type", MediaType.APPLICATION_ATOM_XML); connection.setDoOutput(true); entry.writeTo(connection.getOutputStream()); assertEquals(500, connection.getResponseCode()); connection.disconnect(); }
/** * 从Http连接的头信息中获得字符集 * * @param conn HTTP连接对象 * @return 字符集 */ private static String getCharsetFromConn(HttpURLConnection conn) { String charset = conn.getContentEncoding(); if (charset == null || "".equals(charset.trim())) { String contentType = conn.getContentType(); charset = RegexUtil.get("charset=(.*)", contentType, 1); } return charset; }
@Override protected byte[] send( final byte[] request, final URL responderURL, final RequestOptions requestOptions) throws IOException { int size = request.length; HttpURLConnection httpUrlConnection; if (size <= MAX_LEN_GET && requestOptions.isUseHttpGetForRequest()) { String b64Request = Base64.toBase64String(request); String urlEncodedReq = URLEncoder.encode(b64Request, "UTF-8"); StringBuilder urlBuilder = new StringBuilder(); String baseUrl = responderURL.toString(); urlBuilder.append(baseUrl); if (!baseUrl.endsWith("/")) { urlBuilder.append('/'); } urlBuilder.append(urlEncodedReq); URL newURL = new URL(urlBuilder.toString()); httpUrlConnection = (HttpURLConnection) newURL.openConnection(); httpUrlConnection.setRequestMethod("GET"); } else { httpUrlConnection = (HttpURLConnection) responderURL.openConnection(); httpUrlConnection.setDoOutput(true); httpUrlConnection.setUseCaches(false); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Content-Type", CT_REQUEST); httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size)); OutputStream outputstream = httpUrlConnection.getOutputStream(); outputstream.write(request); outputstream.flush(); } InputStream inputstream = httpUrlConnection.getInputStream(); if (httpUrlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) { inputstream.close(); throw new IOException( "bad response: " + httpUrlConnection.getResponseCode() + " " + httpUrlConnection.getResponseMessage()); } String responseContentType = httpUrlConnection.getContentType(); boolean isValidContentType = false; if (responseContentType != null) { if (responseContentType.equalsIgnoreCase(CT_RESPONSE)) { isValidContentType = true; } } if (!isValidContentType) { inputstream.close(); throw new IOException("bad response: mime type " + responseContentType + " not supported!"); } return IoUtil.read(inputstream); }
/** * 从Http连接的头信息中获得字符集 * * @param conn HTTP连接对象 * @return 字符集 */ public static String getCharset(HttpURLConnection conn) { if (conn == null) { return null; } String charset = conn.getContentEncoding(); if (StrUtil.isBlank(charset)) { charset = ReUtil.get(CHARSET_PATTERN, conn.getContentType(), 1); } return charset; }
/** * Downloads a file from a URL * * @param fileURL HTTP URL of the file to be downloaded * @param saveDir path of the directory to save the file * @throws IOException */ public static void downloadFile(String fileURL, String saveDir, int id) throws IOException { URL url = new URL(fileURL); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; // Map<String, List<String>> responceHeader = httpConn.getHeaderFields(); String disposition = httpConn.getHeaderField("Content-Disposition"); String contentType = httpConn.getContentType(); int contentLength = httpConn.getContentLength(); if (disposition != null) { // extracts file name from header field int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { // extracts file name from URL fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); } // System.out.println("Content-Type = " + contentType); System.out.println("Content-Disposition = " + disposition); // System.out.println("Content-Length = " + contentLength); fileName = "id_" + id + "_" + fileName; System.out.println("fileName = " + fileName); // opens input stream from the HTTP connection InputStream inputStream = httpConn.getInputStream(); String saveFilePath = saveDir + File.separator + fileName; // opens an output stream to save into file FileOutputStream outputStream = new FileOutputStream(saveFilePath); int bytesRead = -1; byte[] buffer = new byte[BUFFER_SIZE]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("File downloaded\n"); } else { System.out.println("No file to download. Server replied HTTP code: " + responseCode); } httpConn.disconnect(); }
/** * Retrieves the asset at the given URL on the CaaS server and returns it in Base64 * * @param (@link String) assetURL * @return (@link Response) base64 encoded image * <p>Path for method: "<server address>/CAAS_Hybrid/adapters/CaaS/asset?assetURL={assetURL}" */ @GET @Path("/asset") public Response CAASAssetRequest(@QueryParam("assetURL") String assetURL) throws IOException, URISyntaxException { if (SERVER == null) { connect(); } return Response.ok( new ByteArrayInputStream(IOUtils.toByteArray(openStream(SERVER + assetURL))), urlConnection.getContentType()) .build(); }
@Test @RunAsClient public void testGetAssetBinary(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/binary"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_OCTET_STREAM); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_OCTET_STREAM, connection.getContentType()); // logger.log(LogLevel, getContent(connection)); }
@Test @RunAsClient public void testGetAssetAsJaxB(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_XML, connection.getContentType()); System.out.println(IOUtils.toString(connection.getInputStream())); }
/** * Initializes an {@link HttpEntity} from the given {@link HttpURLConnection}. * * @param connection * @return an HttpEntity populated with data from <code>connection</code>. */ private static HttpEntity entityFromConnection(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream; try { inputStream = connection.getInputStream(); } catch (IOException ioe) { inputStream = connection.getErrorStream(); } entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
private static HttpEntity a(HttpURLConnection httpurlconnection) { BasicHttpEntity basichttpentity = new BasicHttpEntity(); java.io.InputStream inputstream; try { inputstream = httpurlconnection.getInputStream(); } catch (IOException ioexception) { ioexception = httpurlconnection.getErrorStream(); } basichttpentity.setContent(inputstream); basichttpentity.setContentLength(httpurlconnection.getContentLength()); basichttpentity.setContentEncoding(httpurlconnection.getContentEncoding()); basichttpentity.setContentType(httpurlconnection.getContentType()); return basichttpentity; }
@Test public void testPush_UnpackError_TruncatedPack() throws Exception { StringBuilder sb = new StringBuilder(); sb.append(ObjectId.zeroId().name()); sb.append(' '); sb.append(a_blob.name()); sb.append(' '); sb.append("refs/objects/A"); sb.append('\0'); sb.append("report-status"); ByteArrayOutputStream reqbuf = new ByteArrayOutputStream(); PacketLineOut reqpck = new PacketLineOut(reqbuf); reqpck.writeString(sb.toString()); reqpck.end(); packHeader(reqbuf, 1); byte[] reqbin = reqbuf.toByteArray(); URL u = new URL(remoteURI.toString() + "/git-receive-pack"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); try { c.setRequestMethod("POST"); c.setDoOutput(true); c.setRequestProperty("Content-Type", GitSmartHttpTools.RECEIVE_PACK_REQUEST_TYPE); c.setFixedLengthStreamingMode(reqbin.length); OutputStream out = c.getOutputStream(); try { out.write(reqbin); } finally { out.close(); } assertEquals(200, c.getResponseCode()); assertEquals(GitSmartHttpTools.RECEIVE_PACK_RESULT_TYPE, c.getContentType()); InputStream rawin = c.getInputStream(); try { PacketLineIn pckin = new PacketLineIn(rawin); assertEquals("unpack error " + JGitText.get().packfileIsTruncated, pckin.readString()); assertEquals("ng refs/objects/A n/a (unpacker error)", pckin.readString()); assertSame(PacketLineIn.END, pckin.readString()); } finally { rawin.close(); } } finally { c.disconnect(); } }
protected static void checkContentType(HttpURLConnection conn, byte[] data) throws UnrecoverableDownloadException { String contentType = conn.getContentType(); if (contentType != null) { contentType = contentType.toLowerCase(); if (!contentType.startsWith("image/")) { if (log.isTraceEnabled() && contentType.startsWith("text/")) { log.trace("Content (" + contentType + "): " + new String(data)); } throw new UnrecoverableDownloadException( "Content type of the loaded image is unknown: " + contentType, UnrecoverableDownloadException.ERROR_CODE_CONTENT_TYPE); } } }
protected void parseHeaders(HttpURLConnection httpConnection) { String mediaType = null; String contentType = httpConnection.getContentType(); int indexOfSemicolon = contentType.indexOf(';'); if (indexOfSemicolon != -1) { mediaType = contentType.substring(0, indexOfSemicolon).trim(); String parameter = contentType.substring(indexOfSemicolon + 1).trim(); if (parameter.startsWith("charset=")) withDefaultEncoding(parameter.substring(parameter.indexOf('=') + 1).trim()); } else mediaType = contentType.trim(); getBindings().wDefValue("mediaType", mediaType); }
@Test @RunAsClient public void testGetAssetSource(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1/source"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.TEXT_PLAIN); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.TEXT_PLAIN, connection.getContentType()); String result = IOUtils.toString(connection.getInputStream()); assertTrue(result.indexOf("declare Album2") >= 0); assertTrue(result.indexOf("genre2: String") >= 0); }
// set up url, method, header, cookies private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException { method = Connection.Method.valueOf(conn.getRequestMethod()); url = conn.getURL(); statusCode = conn.getResponseCode(); statusMessage = conn.getResponseMessage(); contentType = conn.getContentType(); Map<String, List<String>> resHeaders = conn.getHeaderFields(); processResponseHeaders(resHeaders); // if from a redirect, map previous response cookies into this response if (previousResponse != null) { for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) { if (!hasCookie(prevCookie.getKey())) cookie(prevCookie.getKey(), prevCookie.getValue()); } } }
/** * 执行HTTP请求之后获取到的数据流. * * @param connection * @return */ private HttpEntity entityFromURLConnwction(HttpURLConnection connection) { BasicHttpEntity entity = new BasicHttpEntity(); InputStream inputStream; try { inputStream = connection.getInputStream(); } catch (IOException e) { e.printStackTrace(); inputStream = connection.getErrorStream(); } // TODO : GZIP entity.setContent(inputStream); entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
public static String getResponse(String url) throws IOException { try { HttpURLConnection conn = openConnection(url); String contentType = conn.getContentType(); String encoding = "utf-8"; if (contentType != null && contentType.indexOf("charset=") > 0) { encoding = contentType.split("charset=")[1]; } InputStream is = conn.getInputStream(); byte[] resp = IOUtils.toByteArray(is); conn.disconnect(); return new String(resp, encoding); } catch (MalformedURLException | URISyntaxException e) { logger.error("", e); return ""; } }
/** {@inheritDoc } */ @Override public String getContent() throws IOException, IllegalStateException { URL link = new URL(url); HttpURLConnection con = (HttpURLConnection) link.openConnection(); if (con.getResponseCode() == 200) { BufferedReader buff = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset.forName("UTF-8"))); return readAll(buff); } else { BufferedReader buff = new BufferedReader(new InputStreamReader(con.getErrorStream(), Charset.forName("UTF-8"))); if (con.getContentType().contains("json")) { throw new IllegalStateException(readAll(buff)); } else { throw new IOException(readAll(buff)); } } }
@Test @RunAsClient public void testGetAssetAsAtom(@ArquillianResource URL baseURL) throws Exception { URL url = new URL(baseURL, "rest/packages/restPackage1/assets/model1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty( "Authorization", "Basic " + new Base64().encodeToString(("admin:admin".getBytes()))); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", MediaType.APPLICATION_ATOM_XML); connection.connect(); assertEquals(200, connection.getResponseCode()); assertEquals(MediaType.APPLICATION_ATOM_XML, connection.getContentType()); // System.out.println(getContent(connection)); InputStream in = connection.getInputStream(); assertNotNull(in); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals( baseURL.getPath() + "rest/packages/restPackage1/assets/model1", entry.getBaseUri().getPath()); assertEquals("model1", entry.getTitle()); assertNotNull(entry.getPublished()); assertNotNull(entry.getAuthor().getName()); assertEquals("desc for model1", entry.getSummary()); // assertEquals(MediaType.APPLICATION_OCTET_STREAM_TYPE.getType(), // entry.getContentMimeType().getPrimaryType()); assertEquals( baseURL.getPath() + "rest/packages/restPackage1/assets/model1/binary", entry.getContentSrc().getPath()); ExtensibleElement metadataExtension = entry.getExtension(Translator.METADATA); ExtensibleElement archivedExtension = metadataExtension.getExtension(Translator.ARCHIVED); assertEquals("false", archivedExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement stateExtension = metadataExtension.getExtension(Translator.STATE); assertEquals("Draft", stateExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement formatExtension = metadataExtension.getExtension(Translator.FORMAT); assertEquals("model.drl", formatExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement uuidExtension = metadataExtension.getExtension(Translator.UUID); assertNotNull(uuidExtension.getSimpleExtension(Translator.VALUE)); ExtensibleElement categoryExtension = metadataExtension.getExtension(Translator.CATEGORIES); assertEquals( "AssetPackageResourceTestCategory", categoryExtension.getSimpleExtension(Translator.VALUE)); }
@Test public void testDoGet() throws Exception { System.out.println("doGet"); HttpURLConnection con = null; try { con = (HttpURLConnection) new URL("http://" + getHost() + "/lenna.jpg").openConnection(); con.setRequestMethod("GET"); con.connect(); assertEquals(HttpURLConnection.HTTP_OK, con.getResponseCode()); assertTrue(con.getContentLength() > 1); assertEquals("image/jpeg", con.getContentType()); } finally { if (con != null) { con.disconnect(); } } }
@Override public InputStream openInputStream() throws RepositoryException { try { HttpURLConnection conn = getRepository() .getResourceHTTPConnection(getLocation().getPath(), EntryStreamType.BLOB, false); conn.setDoOutput(false); conn.setDoInput(true); try { mimeType = conn.getContentType(); return conn.getInputStream(); } catch (IOException e) { throw new RepositoryException( "Cannot download object: " + conn.getResponseCode() + ": " + conn.getResponseMessage(), e); } } catch (IOException e) { throw new RepositoryException("Cannot open connection to '" + getLocation() + "': " + e, e); } }
private void readResponseHeaders(HttpURLConnection conn) { info.disposition = conn.getHeaderField("Content-Disposition"); info.location = conn.getHeaderField("Content-Location"); info.mimeType = DLUtil.normalizeMimeType(conn.getContentType()); final String transferEncoding = conn.getHeaderField("Transfer-Encoding"); if (TextUtils.isEmpty(transferEncoding)) { try { info.totalBytes = Integer.parseInt(conn.getHeaderField("Content-Length")); LogUtils.e("安装包的大小:" + info.totalBytes); } catch (NumberFormatException e) { info.totalBytes = -1; } } else { info.totalBytes = -1; } if (info.totalBytes == -1 && (TextUtils.isEmpty(transferEncoding) || !transferEncoding.equalsIgnoreCase("chunked"))) throw new RuntimeException("Can not obtain size of download file."); if (TextUtils.isEmpty(info.fileName)) info.fileName = DLUtil.obtainFileName(info.realUrl, info.disposition, info.location); }
/** * Returns true if the content type of the resource pointed by sourceString is an image. * * @param sourceString the original image link. * @return true if the content type of the resource pointed by sourceString is an image. */ @Override public boolean isDirectImage(String sourceString) { boolean isDirectImage = false; try { URL url = new URL(sourceString); String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); isDirectImage = connection.getContentType().contains("image"); connection.disconnect(); } else if (protocol.equals("ftp")) { if (sourceString.endsWith(".png") || sourceString.endsWith(".jpg") || sourceString.endsWith(".gif")) { isDirectImage = true; } } } catch (Exception e) { logger.debug("Failed to retrieve content type information for" + sourceString, e); } return isDirectImage; }
Response readResponse(HttpURLConnection connection) throws IOException { int status = connection.getResponseCode(); String reason = connection.getResponseMessage(); List<Header> headers = new ArrayList<Header>(); for (Map.Entry<String, List<String>> field : connection.getHeaderFields().entrySet()) { String name = field.getKey(); for (String value : field.getValue()) { headers.add(new Header(name, value)); } } String mimeType = connection.getContentType(); int length = connection.getContentLength(); InputStream stream; if (status >= 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); } TypedInput responseBody = new TypedInputStream(mimeType, length, stream); return new Response(status, reason, headers, responseBody); }