下面列出了java.net.HttpURLConnection#getHeaderFieldKey ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 获取远程文件大小
*/
public static long getRemoteFileSize(String remoteFileUrl) throws IOException {
long fileSize = 0;
HttpURLConnection httpConnection = (HttpURLConnection) new URL(remoteFileUrl).openConnection();
httpConnection.setRequestMethod("HEAD");
int responseCode = httpConnection.getResponseCode();
if (responseCode >= 400) {
logger.debug("Web服务器响应错误!");
return 0;
}
String sHeader;
for (int i = 1; ; i++) {
sHeader = httpConnection.getHeaderFieldKey(i);
if (sHeader != null && sHeader.equals("Content-Length")) {
logger.info("文件大小ContentLength:"+ httpConnection.getContentLength());
fileSize = Long.parseLong(httpConnection.getHeaderField(sHeader));
break;
}
}
return fileSize;
}
private String followRedirect(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection)
new URL(url).openConnection();
connection.setInstanceFollowRedirects(false);
int code = connection.getResponseCode();
if (code != HttpURLConnection.HTTP_MOVED_TEMP) {
throw new IOException("Unexpected response: " + code + " for " + url +
", with contents: " + drainStream(connection.getInputStream()));
}
int n = 0;
String name, value;
while ((name = connection.getHeaderFieldKey(n)) != null) {
value = connection.getHeaderField(n);
if (name.equals("Location")) {
return value;
}
++n;
}
throw new IOException("Didn't find Location header!");
}
public boolean UpdateCookie(HttpURLConnection conn) {
if (conn == null)
return false;
String key = null;
String cookieVal = null;
for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
if (key.equalsIgnoreCase("set-cookie")) {
NLog.d(LOG_TAG, conn.getHeaderFieldKey(i) + ":"
+ conn.getHeaderField(i));
cookieVal = conn.getHeaderField(i);
UpdateCookie(cookieVal);
}
}
return true;
}
private static LinkedHashMap<String, List<String>> createHeaderMap(HttpURLConnection conn) {
// the default sun impl of conn.getHeaderFields() returns header values out of order
final LinkedHashMap<String, List<String>> headers = new LinkedHashMap<>();
int i = 0;
while (true) {
final String key = conn.getHeaderFieldKey(i);
final String val = conn.getHeaderField(i);
if (key == null && val == null)
break;
i++;
if (key == null || val == null)
continue; // skip http1.1 line
if (headers.containsKey(key))
headers.get(key).add(val);
else {
final ArrayList<String> vals = new ArrayList<>();
vals.add(val);
headers.put(key, vals);
}
}
return headers;
}
private static LinkedHashMap<String, List<String>> createHeaderMap(HttpURLConnection conn) {
// the default sun impl of conn.getHeaderFields() returns header values out of order
final LinkedHashMap<String, List<String>> headers = new LinkedHashMap<>();
int i = 0;
while (true) {
final String key = conn.getHeaderFieldKey(i);
final String val = conn.getHeaderField(i);
if (key == null && val == null)
break;
i++;
if (key == null || val == null)
continue; // skip http1.1 line
if (headers.containsKey(key))
headers.get(key).add(val);
else {
final ArrayList<String> vals = new ArrayList<>();
vals.add(val);
headers.put(key, vals);
}
}
return headers;
}
private String followRedirect(String url) throws IOException {
HttpURLConnection connection = (HttpURLConnection)
new URL(url).openConnection();
connection.setInstanceFollowRedirects(false);
int code = connection.getResponseCode();
if (code != HttpURLConnection.HTTP_MOVED_TEMP) {
throw new IOException("Unexpected response: " + code + " for " + url +
", with contents: " + drainStream(connection.getInputStream()));
}
int n = 0;
String name, value;
while ((name = connection.getHeaderFieldKey(n)) != null) {
value = connection.getHeaderField(n);
if (name.equals("Location")) {
return value;
}
++n;
}
throw new IOException("Didn't find Location header!");
}
private void getCookie(HttpURLConnection conn) {
StringBuilder fullCookie = new StringBuilder();
String cookieVal;
String key;
//取cookie
for (int i = 1; (key = conn.getHeaderFieldKey(i)) != null; i++) {
if ("set-cookie".equalsIgnoreCase(key)) {
cookieVal = conn.getHeaderField(i);
cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
fullCookie.append(cookieVal).append(";");
}
}
store.addCookie(fullCookie.toString());
}
public static InputStream getHttpPostAsStream(URL url, String s, Map map, String s1, String s2)
{
if (url == null)
{
throw new IllegalArgumentException("url");
}
HttpURLConnection.setFollowRedirects(true);
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setConnectTimeout(5000);
httpurlconnection.setReadTimeout(15000);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setDoOutput(true);
if (!TextUtils.isEmpty(s1))
{
httpurlconnection.setRequestProperty("User-Agent", s1);
}
if (!TextUtils.isEmpty(s2))
{
httpurlconnection.setRequestProperty("Cookie", s2);
}
httpurlconnection.getOutputStream().write(s.getBytes());
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
map.put("ResponseCode", (new StringBuilder(String.valueOf(httpurlconnection.getResponseCode()))).toString());
int i = 0;
do
{
String s3 = httpurlconnection.getHeaderFieldKey(i);
String s4 = httpurlconnection.getHeaderField(i);
if (s3 == null && s4 == null)
{
return httpurlconnection.getInputStream();
}
map.put(s3, s4);
i++;
} while (true);
}
public static InputStream getHttpPostAsStream(URL url, String s, Map map, String s1, String s2)
{
if (url == null)
{
throw new IllegalArgumentException("url");
}
HttpURLConnection.setFollowRedirects(true);
HttpURLConnection httpurlconnection = (HttpURLConnection)url.openConnection();
httpurlconnection.setConnectTimeout(5000);
httpurlconnection.setReadTimeout(15000);
httpurlconnection.setRequestMethod("POST");
httpurlconnection.setDoOutput(true);
if (!TextUtils.isEmpty(s1))
{
httpurlconnection.setRequestProperty("User-Agent", s1);
}
if (!TextUtils.isEmpty(s2))
{
httpurlconnection.setRequestProperty("Cookie", s2);
}
httpurlconnection.getOutputStream().write(s.getBytes());
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
map.put("ResponseCode", (new StringBuilder(String.valueOf(httpurlconnection.getResponseCode()))).toString());
int i = 0;
do
{
String s3 = httpurlconnection.getHeaderFieldKey(i);
String s4 = httpurlconnection.getHeaderField(i);
if (s3 == null && s4 == null)
{
return httpurlconnection.getInputStream();
}
map.put(s3, s4);
i++;
} while (true);
}
/**
* Sending an api request through Http GET
*
* @param command command name
* @param params command query parameters in a HashMap
* @return http request response string
*/
protected String sendRequest(final String command, final HashMap<String, String> params) {
try {
// Construct query string
final StringBuilder sBuilder = new StringBuilder();
sBuilder.append("command=");
sBuilder.append(command);
if (params != null && params.size() > 0) {
final Iterator<String> keys = params.keySet().iterator();
while (keys.hasNext()) {
final String key = keys.next();
sBuilder.append("&");
sBuilder.append(key);
sBuilder.append("=");
sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8"));
}
}
// Construct request url
final String reqUrl = rootUrl + "?" + sBuilder.toString();
// Send Http GET request
final URL url = new URL(reqUrl);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (!command.equals("login") && cookieToSent != null) {
// add the cookie to a request
conn.setRequestProperty("Cookie", cookieToSent);
}
conn.connect();
if (command.equals("login")) {
// if it is login call, store cookie
String headerName;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
final String cookieName = cookie.substring(0, cookie.indexOf("="));
final String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookieToSent = cookieName + "=" + cookieValue;
}
}
}
// Get the response
final StringBuilder response = new StringBuilder();
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
try {
while ((line = rd.readLine()) != null) {
response.append(line);
}
} catch (final EOFException ex) {
// ignore this exception
System.out.println("EOF exception due to java bug");
}
rd.close();
return response.toString();
} catch (final Exception e) {
throw new CloudRuntimeException("Problem with sending api request", e);
}
}
/**
* Sending an api request through Http GET
*
* @param command command name
* @param params command query parameters in a HashMap
* @return http request response string
*/
protected String sendRequest(final String command, final HashMap<String, String> params) {
try {
// Construct query string
final StringBuilder sBuilder = new StringBuilder();
sBuilder.append("command=");
sBuilder.append(command);
if (params != null && params.size() > 0) {
final Iterator<String> keys = params.keySet().iterator();
while (keys.hasNext()) {
final String key = keys.next();
sBuilder.append("&");
sBuilder.append(key);
sBuilder.append("=");
sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8"));
}
}
// Construct request url
final String reqUrl = rootUrl + "?" + sBuilder.toString();
// Send Http GET request
final URL url = new URL(reqUrl);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (!command.equals("login") && cookieToSent != null) {
// add the cookie to a request
conn.setRequestProperty("Cookie", cookieToSent);
}
conn.connect();
if (command.equals("login")) {
// if it is login call, store cookie
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
final String cookieName = cookie.substring(0, cookie.indexOf("="));
final String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookieToSent = cookieName + "=" + cookieValue;
}
}
}
// Get the response
final StringBuilder response = new StringBuilder();
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
try {
while ((line = rd.readLine()) != null) {
response.append(line);
}
} catch (final EOFException ex) {
// ignore this exception
System.out.println("EOF exception due to java bug");
}
rd.close();
return response.toString();
} catch (final Exception e) {
throw new CloudRuntimeException("Problem with sending api request", e);
}
}
/**
* NGW API Functions
*/
public static String getConnectionCookie(
AtomicReference<String> reference,
String login,
String password)
throws IOException
{
String sUrl = reference.get();
if (!sUrl.startsWith("http")) {
sUrl = "http://" + sUrl;
reference.set(sUrl);
}
sUrl += "/login";
String sPayload = "login=" + login + "&password=" + password;
final HttpURLConnection conn = NetworkUtil.getHttpConnection("POST", sUrl, null, null);
if (null == conn) {
Log.d(TAG, "Error get connection object: " + sUrl);
return null;
}
conn.setInstanceFollowRedirects(false);
conn.setDefaultUseCaches(false);
conn.setDoOutput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(sPayload);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (!(responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM)) {
Log.d(TAG, "Problem execute post: " + sUrl + " HTTP response: " + responseCode);
return null;
}
String headerName;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
return conn.getHeaderField(i);
}
}
if (!sUrl.startsWith("https")) {
sUrl = sUrl.replace("http", "https").replace("/login", "");
reference.set(sUrl);
}
return getConnectionCookie(reference, login, password);
}
/**
* Sending an api request through Http GET
* @param command command name
* @param params command query parameters in a HashMap
* @return http request response string
*/
protected String sendRequest(String command, HashMap<String, String> params) {
try {
// Construct query string
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("command=");
sBuilder.append(command);
if (params != null && params.size() > 0) {
Iterator<String> keys = params.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
sBuilder.append("&");
sBuilder.append(key);
sBuilder.append("=");
sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8"));
}
}
// Construct request url
String reqUrl = rootUrl + "?" + sBuilder.toString();
// Send Http GET request
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (!command.equals("login") && cookieToSent != null) {
// add the cookie to a request
conn.setRequestProperty("Cookie", cookieToSent);
}
conn.connect();
if (command.equals("login")) {
// if it is login call, store cookie
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookieToSent = cookieName + "=" + cookieValue;
}
}
}
// Get the response
StringBuilder response = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
try {
while ((line = rd.readLine()) != null) {
response.append(line);
}
} catch (EOFException ex) {
// ignore this exception
System.out.println("EOF exception due to java bug");
}
rd.close();
return response.toString();
} catch (Exception e) {
throw new CloudRuntimeException("Problem with sending api request", e);
}
}
/**
* Sending an api request through Http GET
* @param command command name
* @param params command query parameters in a HashMap
* @return http request response string
*/
protected String sendRequest(String command, HashMap<String, String> params) {
try {
// Construct query string
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("command=");
sBuilder.append(command);
if (params != null && params.size() > 0) {
Iterator<String> keys = params.keySet().iterator();
while (keys.hasNext()) {
String key = keys.next();
sBuilder.append("&");
sBuilder.append(key);
sBuilder.append("=");
sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8"));
}
}
// Construct request url
String reqUrl = rootUrl + "?" + sBuilder.toString();
// Send Http GET request
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
if (!command.equals("login") && cookieToSent != null) {
// add the cookie to a request
conn.setRequestProperty("Cookie", cookieToSent);
}
conn.connect();
if (command.equals("login")) {
// if it is login call, store cookie
String headerName = null;
for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = conn.getHeaderField(i);
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
cookieToSent = cookieName + "=" + cookieValue;
}
}
}
// Get the response
StringBuilder response = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
try {
while ((line = rd.readLine()) != null) {
response.append(line);
}
} catch (EOFException ex) {
// ignore this exception
System.out.println("EOF exception due to java bug");
}
rd.close();
return response.toString();
} catch (Exception e) {
throw new CloudRuntimeException("Problem with sending api request", e);
}
}