本文整理汇总了Java中java.net.HttpURLConnection.getContentType方法的典型用法代码示例。如果您正苦于以下问题:Java HttpURLConnection.getContentType方法的具体用法?Java HttpURLConnection.getContentType怎么用?Java HttpURLConnection.getContentType使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.HttpURLConnection
的用法示例。
在下文中一共展示了HttpURLConnection.getContentType方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getContentCharset
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private String getContentCharset(HttpURLConnection connection) {
if (connection != null) {
final String contentType = connection.getContentType();
if (contentType != null) {
final String[] values = contentType.split(";"); // values.length should be 2
String charset = null;
if (values != null) {
for (String value : values) {
value = value.trim();
if (value != null && value.toLowerCase().startsWith("charset=")) {
charset = value.substring("charset=".length());
}
}
}
return charset;
}
}
return null;
}
示例2: makeContent
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* 得到响应对象
*
* @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,
Charset.forName(this.defaultContentEncoding)));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("");
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 = temp.toString();
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();
}
}
示例3: fetchContentInfo
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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();
}
}
}
示例4: downloadAndPipe
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private static void downloadAndPipe(String url, UrlType urlType, String uuid, String username, OutputStream out) throws IOException {
url = replaceUrlObjects(url, uuid, username);
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection)urlObj.openConnection();
String type = con.getContentType();
InputStream in = con.getInputStream();
if(urlType != UrlType.TEXTURES && (type.equals("application/json") || type.startsWith("text"))) {
// The game expects an image, not a json
url = CONFIG.getFromJson(new JsonParser().parse(new InputStreamReader(in)), urlType);
downloadAndPipe(url, urlType, uuid, username, out);
return;
}
// This is exactly what the game expects. Let's give it what it wants :)
serverPipe(in, type, con.getContentLengthLong(), out);
}
示例5: checkServiceAvailable
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Checks if the service is reachable (test is performed online) and if
* prefix.cc sends information with the correct content type.
* @return
*/
private boolean checkServiceAvailable(){
try {
HttpURLConnection con = (HttpURLConnection)PrefixccProvider.GET_ALL.openConnection();
con.setReadTimeout(5000); //set the max connect & read timeout to 5sec
con.setConnectTimeout(5000);
con.connect();
String contentType = con.getContentType();
IOUtils.closeQuietly(con.getInputStream()); //close the stream
if("text/plain".equalsIgnoreCase(contentType)){
return true;
} else {
log.info("Request to http://prefix.cc ... returned an unexpected "
+ "ContentType "+contentType+ " (expected: text/plain) "
+ " ... deactivate" + PrefixccProvider.class.getSimpleName()
+ " test");
return false; //service seams to be down ... skip tests
}
} catch (IOException e) {
log.info("Unable to connect to http://prefix.cc ... deactivating "
+ PrefixccProvider.class.getSimpleName()+ " test");
return false;
}
}
示例6: jsonParse
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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();
}
}
示例7: getEncoding
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public String getEncoding(HttpURLConnection connection) {
String contentType = connection.getContentType();
String[] values = contentType.split(";"); // values.length should be 2
String charset = "";
for (String value : values) {
value = value.trim();
if (value.toLowerCase().startsWith("charset=")) {
charset = value.substring("charset=".length());
}
}
return charset;
}
示例8: Response
import java.net.HttpURLConnection; //导入方法依赖的package包/类
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());
}
示例9: downloadFile
import java.net.HttpURLConnection; //导入方法依赖的package包/类
public static void downloadFile(String sourceURL,String fileNameWithPath) throws IOException{
final int BUFFER_SIZE = 4096;
URL url = new URL(sourceURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
int index = disposition.indexOf("file=");
if (index > 0)
fileName = disposition.substring(index + 10,disposition.length() - 1);
} else {
fileName = sourceURL.substring(sourceURL.lastIndexOf("/") + 1,sourceURL.length());
}
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(fileNameWithPath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
httpConn.disconnect();
}
示例10: getContentType
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private ContentType getContentType(URL fileLocation) {
try {
HttpURLConnection connection = (HttpURLConnection)fileLocation.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
String contentTypeHeader = connection.getContentType();
if (contentTypeHeader != null) {
Matcher matcher = CONTENT_TYPE_PATTERN.matcher(contentTypeHeader.trim().toLowerCase(Locale.ENGLISH));
if (matcher.matches()) {
ContentType contentType = new ContentType();
String contentTypeString = matcher.group(1);
String charsetString = matcher.group(3);
if (contentTypeString != null) {
contentType.type = contentTypeString.trim();
}
if (charsetString != null) {
contentType.charset = charsetString.trim();
}
return contentType;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
示例11: getResponse
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@Override
public ResponseScriptType getResponse(boolean isGET)
{
try
{
final String data = getFormData();
String extra = "";
if( isGET && !Check.isEmpty(data) )
{
String qs = url.getQuery();
if( Check.isEmpty(qs) )
{
extra += "?" + data;
}
else
{
extra += "?" + qs + "&" + data;
}
}
final String urlString = url.toString() + extra;
final URL finalUrl = new URL(urlString);
final HttpURLConnection conn = (HttpURLConnection) finalUrl.openConnection();
conn.setRequestMethod(isGET ? "GET" : "POST");
conn.setAllowUserInteraction(false);
conn.setInstanceFollowRedirects(true);
conn.setDoOutput(true);
conn.setDoInput(true);
// Send data
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "*/*");
if( !isGET )
{
try( Writer wr = new OutputStreamWriter(conn.getOutputStream()) )
{
if( !isGET )
{
wr.write(data);
}
wr.flush();
}
}
// Get the response
final String contentType = conn.getContentType();
try( InputStream is = conn.getInputStream() )
{
if( contentType == null || contentType.startsWith("text/") )
{
Reader rd = new InputStreamReader(is);
StringWriter sw = new StringWriter();
CharStreams.copy(rd, sw);
return new ResponseScriptTypeImpl(sw.toString(), conn.getResponseCode(), contentType);
}
else
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteStreams.copy(is, os);
return new ResponseScriptTypeImpl(os.toByteArray(), conn.getResponseCode(), contentType);
}
}
}
catch( IOException e )
{
return new ResponseScriptTypeImpl("ERROR: " + e.getMessage(), 400, "text/plain");
}
}
示例12: getContentType
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private ContentType getContentType(URL fileLocation) {
try {
HttpURLConnection connection = (HttpURLConnection) fileLocation.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
String contentTypeHeader = connection.getContentType();
if (contentTypeHeader != null) {
Matcher matcher = CONTENT_TYPE_PATTERN.matcher(contentTypeHeader.trim().toLowerCase(Locale.ENGLISH));
if (matcher.matches()) {
ContentType contentType = new ContentType();
String contentTypeString = matcher.group(1);
String charsetString = matcher.group(3);
if (contentTypeString != null) {
contentType.type = contentTypeString.trim();
}
if (charsetString != null) {
contentType.charset = charsetString.trim();
}
return contentType;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
示例13: mainFlow
import java.net.HttpURLConnection; //导入方法依赖的package包/类
/**
* Executes the main flow of the soap usecase;
*/
@Override
protected void mainFlow(UsecaseExecution<TParams, TResult> execution) throws Exception {
URL url = getUrl();
DocumentBuilder documentBuilder = BUILDER_FACTORY.newDocumentBuilder();
// Builds the entire request xml;
Document xmlrequest = documentBuilder.newDocument();
Element xmlenvelope = createEnvelopeElement(xmlrequest);
Element xmlheader = createHeaderElement(xmlenvelope);
Object soapHeader = execution.headers == null
? null
: execution.headers.get("soap");
if (soapHeader != null)
XmlAspect.getInstance(soapHeader.getClass()).format(soapHeader, xmlheader);
Element xmlbody = createBodyElement(xmlenvelope);
XmlAspect.getInstance(getParamsClass()).format(execution.params, xmlbody);
// debugging
if (is_debugging)
System.out.println(new StringAdapter().convertXml(xmlrequest));
// Sends the document to output;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/xml");
TRANSFORMER_FACTORY.newTransformer().transform(
new DOMSource(xmlrequest),
new StreamResult(connection.getOutputStream()));
try {
String contentType = connection.getContentType();
String charSet = (contentType != null && contentType.contains("charset="))
? contentType.substring(contentType.indexOf('=') + 1)
: "UTF-8";
InputStream inputStream = connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(inputStream, charSet);
// Reads the response xml
Document xmlresponse = documentBuilder.parse(new InputSource(isReader));
// Debugging
if (is_debugging)
System.out.println(new StringAdapter().convertXml(xmlresponse));
isReader.close();
inputStream.close();
connection.disconnect();
NodeList headerList = xmlresponse.getElementsByTagName("soap:Header");
if (headerList != null && headerList.getLength() == 1)
processResponseHeader((Element) headerList.item(0), execution);
NodeList bodyList = xmlresponse.getElementsByTagName("soap:Body");
if (bodyList == null || bodyList.getLength() != 1) {
execution.result_type = UsecaseResultType.EXECUTION_FAILED;
execution.exception = new Exception("SOAP Body not found on response");
return;
}
// Processes the response xml;
processResponseBody((Element) bodyList.item(0), execution);
} catch (IOException ioe) {
System.out.println(new StringAdapter().convertStream(connection.getErrorStream()));
execution.exception = ioe;
execution.result_type = UsecaseResultType.EXECUTION_FAILED;
}
}
示例14: call
import java.net.HttpURLConnection; //导入方法依赖的package包/类
private <T> T call(HttpURLConnection conn, Map jsonOutput,
int expectedResponse, Class<T> klass, int authRetryCount)
throws IOException {
T ret = null;
try {
if (jsonOutput != null) {
writeJson(jsonOutput, conn.getOutputStream());
}
} catch (IOException ex) {
IOUtils.closeStream(conn.getInputStream());
throw ex;
}
if ((conn.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN
&& (conn.getResponseMessage().equals(ANONYMOUS_REQUESTS_DISALLOWED) ||
conn.getResponseMessage().contains(INVALID_SIGNATURE)))
|| conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
// Ideally, this should happen only when there is an Authentication
// failure. Unfortunately, the AuthenticationFilter returns 403 when it
// cannot authenticate (Since a 401 requires Server to send
// WWW-Authenticate header as well)..
KMSClientProvider.this.authToken =
new DelegationTokenAuthenticatedURL.Token();
if (authRetryCount > 0) {
String contentType = conn.getRequestProperty(CONTENT_TYPE);
String requestMethod = conn.getRequestMethod();
URL url = conn.getURL();
conn = createConnection(url, requestMethod);
conn.setRequestProperty(CONTENT_TYPE, contentType);
return call(conn, jsonOutput, expectedResponse, klass,
authRetryCount - 1);
}
}
try {
AuthenticatedURL.extractToken(conn, authToken);
} catch (AuthenticationException e) {
// Ignore the AuthExceptions.. since we are just using the method to
// extract and set the authToken.. (Workaround till we actually fix
// AuthenticatedURL properly to set authToken post initialization)
}
HttpExceptionUtils.validateResponse(conn, expectedResponse);
if (conn.getContentType() != null
&& conn.getContentType().trim().toLowerCase()
.startsWith(APPLICATION_JSON_MIME)
&& klass != null) {
ObjectMapper mapper = new ObjectMapper();
InputStream is = null;
try {
is = conn.getInputStream();
ret = mapper.readValue(is, klass);
} finally {
IOUtils.closeStream(is);
}
}
return ret;
}
示例15: saveImageInner
import java.net.HttpURLConnection; //导入方法依赖的package包/类
@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;
}