下面列出了java.net.HttpURLConnection#getContentType ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void fetchContentInfo() throws ProxyCacheException {
KLog.d("Read content info from " + sourceInfo.url);
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = openConnection(0, 10000);
long length = getContentLength(urlConnection);
String mime = urlConnection.getContentType();
inputStream = urlConnection.getInputStream();
this.sourceInfo = new SourceInfo(sourceInfo.url, length, mime);
this.sourceInfoStorage.put(sourceInfo.url, sourceInfo);
KLog.d("Source info fetched: " + sourceInfo);
} catch (IOException e) {
KLog.e("Error fetching info from " + sourceInfo.url, e);
} finally {
ProxyCacheUtils.close(inputStream);
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
/**
* Try to find the name of the file by using connection information.
*
* @param connection
* HTTP connection
* @return File name
*/
private static String getFileName(HttpURLConnection connection) {
String fileName = getLastSegmentUrl(connection.getURL().toString());
String contentType = connection.getContentType();
if (contentType != null) {
MediaType type = MediaType.parse(contentType);
if (type.is(MediaType.ANY_APPLICATION_TYPE)) {
String contentDisposition = connection.getHeaderField(CONTENT_DISPOSITION);
if (contentDisposition != null) {
String[] content = contentDisposition.split(";"); //$NON-NLS-1$
for (String string : content) {
if (string.contains("filename=")) { //$NON-NLS-1$
int index = string.indexOf('"');
fileName = string.substring(index + 1, string.length() - 1);
}
}
}
}
}
return fileName;
}
private static String getCharset(HttpURLConnection conn) {
String contentType = conn.getContentType();
if (StringUtils.isEmpty(contentType)) {
return DEFAULT_CONTENT_TYPE;
}
String[] values = contentType.split(";");
if (values.length == 0) {
return DEFAULT_CONTENT_TYPE;
}
String charset = DEFAULT_CONTENT_TYPE;
for (String value : values) {
value = value.trim();
if (value.toLowerCase().startsWith("charset=")) {
charset = value.substring("charset=".length());
}
}
return charset;
}
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
) throws IOException {
if (c.getContentLength() == 0) {
return null;
}
final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
if (in == null) {
throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
}
try {
final String contentType = c.getContentType();
if (contentType != null) {
final MediaType parsed = MediaType.valueOf(contentType);
if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
throw new IOException("Content-Type \"" + contentType
+ "\" is incompatible with \"" + MediaType.APPLICATION_JSON
+ "\" (parsed=\"" + parsed + "\")");
}
}
ObjectMapper mapper = new ObjectMapper();
return mapper.reader(Map.class).readValue(in);
} finally {
in.close();
}
}
private void fetchContentInfo() throws ProxyCacheException {
LOG.debug("Read content info from " + sourceInfo.url);
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = openConnection(0, 10000);
long length = getContentLength(urlConnection);
String mime = urlConnection.getContentType();
inputStream = urlConnection.getInputStream();
this.sourceInfo = new SourceInfo(sourceInfo.url, length, mime);
this.sourceInfoStorage.put(sourceInfo.url, sourceInfo);
LOG.debug("Source info fetched: " + sourceInfo);
} catch (IOException e) {
LOG.error("Error fetching info from " + sourceInfo.url, e);
} finally {
ProxyCacheUtils.close(inputStream);
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
) throws IOException {
if (c.getContentLength() == 0) {
return null;
}
final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
if (in == null) {
throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
}
try {
final String contentType = c.getContentType();
if (contentType != null) {
final MediaType parsed = MediaType.valueOf(contentType);
if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
throw new IOException("Content-Type \"" + contentType
+ "\" is incompatible with \"" + MediaType.APPLICATION_JSON
+ "\" (parsed=\"" + parsed + "\")");
}
}
ObjectMapper mapper = new ObjectMapper();
return mapper.reader(Map.class).readValue(in);
} finally {
in.close();
}
}
private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException {
method = Method.valueOf(conn.getRequestMethod());
url = conn.getURL();
statusCode = conn.getResponseCode();
statusMessage = conn.getResponseMessage();
contentType = conn.getContentType();
Map<String, List<String>> resHeaders = createHeaderMap(conn);
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());
}
}
}
/**
* The ResponseContainer reads a {@link HttpURLConnection} to keep the data even if the connection does not exist
* any longer. Can copy the {@link InputStream} unless keepOriginalStream is set to true.
*
* @param connection to read and copy from
* @param keepOriginalStream will forward access to the original URLConnection {@link InputStream}, reading this may
* fail if the connection was closed in between.
* @throws IOException in case accessing the server failed technically
*/
public ResponseContainer(HttpURLConnection connection, boolean keepOriginalStream) throws IOException {
// we need to keep a copy here to hold the data even if the connection was closed
if (connection.getDoOutput()) {
outputStream = nil -> connection.getOutputStream();
responseCode = nil -> connection.getResponseCode();
responseMessage = nil -> connection.getResponseMessage();
contentType = connection::getContentType;
} else {
int responseCd = connection.getResponseCode();
responseCode = nil -> responseCd;
String responseMsg = connection.getResponseMessage();
responseMessage = nil -> responseMsg;
String contentTyp = connection.getContentType();
contentType = () -> contentTyp;
}
if (connection.getDoInput()) {
// cannot write output after reading input, so this needs to keep the original
if (connection.getDoOutput() || keepOriginalStream) {
inputStream = nil -> connection.getInputStream();
} else {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(IOUtils.toByteArray(connection.getInputStream()));
inputStream = nil -> byteArrayInputStream;
connection.disconnect();
}
}
}
public Response(HttpURLConnection connection) throws IOException {
this.code = connection.getResponseCode();
this.contentLength = connection.getContentLength();
this.contentType = connection.getContentType();
this.headers = connection.getHeaderFields();
this.data = ByteStreams.toByteArray(connection.getInputStream());
}
/**
* 通过HTTP GET方式下载文件到指定的目录。
*
* @param url 需要下载的URL
* @param toDir 需要下载到的目录
* @return 下载后的文件
*/
public static File download(String url, File toDir) throws AlipayApiException {
toDir.mkdirs();
HttpURLConnection conn = null;
OutputStream output = null;
File file = null;
try {
conn = getConnection(new URL(url));
String ctype = conn.getContentType();
if (CTYPE_OCTET.equals(ctype)) {
String fileName = getFileName(conn);
file = new File(toDir, fileName);
output = new FileOutputStream(file);
copy(conn.getInputStream(), output);
} else {
String rsp = WebUtils.getResponseAsString(conn);
throw new AlipayApiException(rsp);
}
} catch (IOException e) {
throw new AlipayApiException(e.getMessage());
} finally {
closeQuietly(output);
if (conn != null) {
conn.disconnect();
}
}
return file;
}
private static BitbucketException fault(final HttpURLConnection http) throws IOException {
final int responseCode = http.getResponseCode();
try (final InputStream stream =
(responseCode >= 400 ? http.getErrorStream() : http.getInputStream())) {
String body = null;
if (stream != null) {
final int length = http.getContentLength();
body = readBody(stream, length);
}
return new BitbucketException(responseCode, body, http.getContentType());
}
}
private byte[] httpGet(String url, String responseCt) throws IOException {
HttpURLConnection conn = SdkUtil.openHttpConn(new URL(url));
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + authorization);
InputStream inputStream = conn.getInputStream();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
inputStream.close();
throw new IOException("bad response: " + conn.getResponseCode() + " "
+ conn.getResponseMessage());
}
String responseContentType = conn.getContentType();
boolean isValidContentType = false;
if (responseContentType != null) {
if (responseContentType.equalsIgnoreCase(responseCt)) {
isValidContentType = true;
}
}
if (!isValidContentType) {
inputStream.close();
throw new IOException("bad response: mime type " + responseContentType + " not supported!");
}
return SdkUtil.read(inputStream);
}
public static byte[] send(URL url, String httpMethod, byte[] request, String requestContentType,
String expectedResponseContentType) throws IOException {
HttpURLConnection httpUrlConnection = SdkUtil.openHttpConn(url);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod(httpMethod);
if (requestContentType != null) {
httpUrlConnection.setRequestProperty("Content-Type", requestContentType);
}
if (request != null) {
httpUrlConnection.setRequestProperty("Content-Length", Integer.toString(request.length));
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(expectedResponseContentType)) {
isValidContentType = true;
}
}
if (!isValidContentType) {
inputStream.close();
throw new IOException("bad response: mime type " + responseContentType + " not supported!");
}
return SdkUtil.read(inputStream);
}
/**
* 得到响应对象
* @param urlConnection
* @param content 网页内容
* @return 响应对象
* @throws IOException
*/
private HttpResponse makeContent(String urlString, HttpURLConnection urlConnection, String content) throws IOException {
HttpResponse httpResponser = new HttpResponse();
try {
httpResponser.contentCollection = new Vector<String>();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.encode;
httpResponser.urlString = urlString;
this.cookies=urlConnection.getHeaderField("Set-Cookie");
httpResponser.cookie=this.cookies;
httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo();
httpResponser.content = content;
httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout();
httpResponser.headerFields = urlConnection.getHeaderFields();
return httpResponser;
} catch (IOException e) {
throw e;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
/**
* 得到响应对象
*
* @param urlConnection
* @return 响应对象
* @throws IOException
*/
private HttpRespons makeContent(String urlString,
HttpURLConnection urlConnection) throws IOException {
HttpRespons httpResponser = new HttpRespons();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.defaultContentEncoding;
httpResponser.urlString = urlString;
httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo();
httpResponser.content = new String(temp.toString().getBytes(), ecod);
httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout();
return httpResponser;
} catch (IOException e) {
throw e;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
/**
* 处理响应
*
* @param urlConnection
* @return 响应对象
* @throws java.io.IOException
*/
private HttpResponse makeContent(String urlString,
HttpURLConnection urlConnection) throws IOException {
HttpResponse httpResponser = new HttpResponse();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.defaultContentEncoding;
httpResponser.urlString = urlString;
httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo();
httpResponser.content = new String(temp.toString().getBytes(), ecod);
httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout();
return httpResponser;
} catch (IOException e) {
throw e;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
private byte[] transmit(MgmtAction action, MgmtRequest req, boolean voidReturn)
throws CaMgmtException {
initIfNotDone();
byte[] reqBytes = req == null ? null : JSON.toJSONBytes(req);
int size = reqBytes == null ? 0 : reqBytes.length;
URL url = actionUrlMap.get(action);
try {
HttpURLConnection httpUrlConnection = IoUtil.openHttpConn(url);
if (httpUrlConnection instanceof HttpsURLConnection) {
if (sslSocketFactory != null) {
((HttpsURLConnection) httpUrlConnection).setSSLSocketFactory(sslSocketFactory);
}
if (hostnameVerifier != null) {
((HttpsURLConnection) httpUrlConnection).setHostnameVerifier(hostnameVerifier);
}
}
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-Type", REQUEST_CT);
httpUrlConnection.setRequestProperty("Content-Length", java.lang.Integer.toString(size));
OutputStream outputstream = httpUrlConnection.getOutputStream();
if (size != 0) {
outputstream.write(reqBytes);
}
outputstream.flush();
if (httpUrlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = httpUrlConnection.getInputStream();
boolean inClosed = false;
try {
String responseContentType = httpUrlConnection.getContentType();
if (!RESPONSE_CT.equals(responseContentType)) {
throw new CaMgmtException(
"bad response: mime type " + responseContentType + " not supported!");
}
if (voidReturn) {
return null;
} else {
inClosed = true;
return IoUtil.read(httpUrlConnection.getInputStream());
}
} finally {
if (in != null & !inClosed) {
in.close();
}
}
} else {
String errorMessage = httpUrlConnection.getHeaderField(HttpConstants.HEADER_XIPKI_ERROR);
if (errorMessage == null) {
StringBuilder sb = new StringBuilder(100);
sb.append("server returns ").append(httpUrlConnection.getResponseCode());
String respMsg = httpUrlConnection.getResponseMessage();
if (StringUtil.isNotBlank(respMsg)) {
sb.append(" ").append(respMsg);
}
throw new CaMgmtException(sb.toString());
} else {
throw new CaMgmtException(errorMessage);
}
}
} catch (IOException ex) {
throw new CaMgmtException(
"IOException while sending message to the server: " + ex.getMessage(), ex);
}
}
@NonNull
private static String saveImageInner(String downImgUrl) {
Context context= MainApp.getInstance().getApplicationContext();
File dir = new File(FileAccessor.Image_Download);
if (!dir.exists()) {
dir.mkdirs();
}
String path = "";
InputStream inputStream = null;
try {
URL url = new URL(downImgUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(20000);
int respCode=conn.getResponseCode();
//if (conn.getResponseCode() == 200) {
inputStream = conn.getInputStream();
//}
byte[] buffer = new byte[4096];
int len = 0;
String contentType=conn.getContentType();
String ext= ContentTypeUtil.getExt(conn.getContentType());
long t = new Date().getTime();
String filename = t + ext;
path = FileAccessor.Image_Download + "/" + filename;
File file = new File(path);
FileOutputStream outStream = new FileOutputStream(file);
while ((len = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
addImageToGallery(path, context,contentType);
} catch (Exception e) {
e.printStackTrace();
}
return path;
}
private boolean execute(List<String> args) throws Exception{
File responseFile = getFile(args, ">");
HttpURLConnection con = prepare(args);
if(con==null)
return false;
if(con.getResponseCode()==401){ // Unauthorized
if(authenticate(con))
return execute(args);
else
return false;
}
Ansi result = con.getResponseCode()/100==2 ? SUCCESS : FAILURE;
result.outln(con.getResponseCode()+" "+con.getResponseMessage());
System.out.println();
boolean success = true;
InputStream in = con.getErrorStream();
if(in==null)
in = con.getInputStream();
else
success = false;
PushbackInputStream pin = new PushbackInputStream(in);
int data = pin.read();
if(data==-1){
if(responseFile!=null)
responseFile.delete();
return success;
}
pin.unread(data);
if(success && responseFile!=null){
IOUtil.pump(pin, new FileOutputStream(responseFile), true, true);
return true;
}
String contentType = con.getContentType();
if(Util.isXML(contentType)){
PrintStream sysErr = System.err;
System.setErr(new PrintStream(new ByteArrayOutputStream()));
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(new StreamSource(pin), new SAXResult(new AnsiHandler()));
transformer.reset();
return success;
} catch (Exception ex) {
sysErr.println("response is not valid xml: "+ex.getMessage());
return false;
} finally {
System.setErr(sysErr);
}
}
if(Util.isPlain(contentType) || Util.isJSON(contentType) || Util.isHTML(contentType)){
IOUtil.pump(pin, System.out, true, false);
System.out.println();
}else{
File temp = File.createTempFile("attachment", "."+Util.getExtension(contentType), FileUtil.USER_DIR);
IOUtil.pump(pin, new FileOutputStream(temp), true, true);
System.out.println("response saved to "+temp.getAbsolutePath());
}
return success;
}
/**
* 得到响应对象
* @param urlConnection
* @return 响应对象
* @throws IOException
*/
private HttpResponse makeContent(String urlString, HttpURLConnection urlConnection) throws IOException {
urlConnection.setConnectTimeout(this.timeout);
urlConnection.setReadTimeout(this.timeout);
HttpResponse httpResponser = new HttpResponse();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.encode;
httpResponser.urlString = urlString;
//urlConnection.getHeaderField("Set-Cookie");获取到的COOKIES不全,会将JSESSIONID漏掉,故而采用此中方式
if(this.cookies == null || this.cookies.equals("")){
if(urlConnection.getHeaderFields().get("Set-Cookie") != null){
List<String> listS = urlConnection.getHeaderFields().get("Set-Cookie");
String cookie = "";
if(listS != null){
for (int i = 0; i < listS.size(); i++) {
cookie = cookie + (cookie.equals("")? "":", ") + listS.get(i);
}
}else{
cookie = urlConnection.getHeaderField("Set-Cookie");
}
this.cookies=cookie;
httpResponser.cookie=this.cookies;
}
}
httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo();
httpResponser.content = new String(temp.toString().getBytes(), ecod);
httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout();
httpResponser.headerFields = urlConnection.getHeaderFields();
} catch (IOException e) {
httpResponser.code = 404;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
return httpResponser;
}