android http封装类,HTTP封装类 工具类 For Android
================2013 04 10 解决2.1 认证问题
package com.su.funycard.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
/**
* HttpUtil Class Capsule Most Functions of Http Operations
*
* @author sfshine
*
*/
public class HttpUtil {
private static Header[] headers = new BasicHeader[1];
private static String TAG = "HTTPUTIL";
private static int TIMEOUT = 5 * 1000;
private static final String BOUNDARY = "---------------------------7db1c523809b2";
/**
* Your header of http op
*
* @return
*/
static {
headers[0] = new BasicHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
}
public static boolean delete(String murl) throws Exception {
URL url = new URL(murl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 204) {
MLog.e(conn.toString());
return true;
}
MLog.e(conn.getRequestMethod());
MLog.e(conn.getResponseCode() + "");
return false;
}
/**
* Op Http get request
*
* @param url
* @param map
* Values to request
* @return
*/
static public String get(String url) {
return get(url, null);
}
static public String get(String url, HashMap map) {
HttpClient client = getNewHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
String result = "ERROR";
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
HttpGet get = new HttpGet(url);
get.setHeaders(headers);
Log.i(TAG, url);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// setCookie(response);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* Op Http post request , "404error" response if failed
*
* @param url
* @param map
* Values to request
* @return
*/
static public String post(String url, HashMap map) {
HttpClient client = getNewHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
HttpPost post = new HttpPost(url);
MLog.i(TAG, url);
post.setHeaders(headers);
String result = "ERROR";
ArrayList pairList = new ArrayList();
if (map != null) {
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
BasicNameValuePair pair = new BasicNameValuePair(
entry.getKey(), entry.getValue());
pairList.add(pair);
}
}
try {
HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* 自定义的http请求可以设置为DELETE PUT等而不是GET
*
* @param url
* @param params
* @param method
* @throws IOException
*/
public static String customrequest(String url,
HashMap params, String method) {
try {
URL postUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) postUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod(method);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
conn.connect();
OutputStream out = conn.getOutputStream();
StringBuilder sb = new StringBuilder();
if (null != params) {
int i = params.size();
for (Map.Entry entry : params.entrySet()) {
if (i == 1) {
sb.append(entry.getKey() + "=" + entry.getValue());
} else {
sb.append(entry.getKey() + "=" + entry.getValue() + "&");
}
i--;
}
}
String content = sb.toString();
out.write(content.getBytes("UTF-8"));
out.flush();
out.close();
InputStream inStream = conn.getInputStream();
String result = inputStream2String(inStream);
Log.i(TAG, "result>" + result);
conn.disconnect();
return result;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* 必须严格限制get请求所以增加这个方法 这个方法也可以自定义请求
*
* @param url
* @param method
* @throws Exception
*/
public static String customrequestget(String url,
HashMap map, String method) {
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
try {
URL murl = new URL(url);
System.out.print(url);
HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
InputStream inStream = conn.getInputStream();
String result = inputStream2String(inStream);
Log.i(TAG, "result>" + result);
conn.disconnect();
return result;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* 上传多张图片
*/
public static String post(String actionUrl, Map params,
Map files) {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
try {
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET
+ LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(
conn.getOutputStream());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null) {
for (Map.Entry file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\""
+ file.getKey() + "\"; filename=\""
+ file.getValue().getName() + "\"" + LINEND);
sb1.append("Content-Type: image/pjpeg; " + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND)
.getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
// if (res == 200) {
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
// }
outStream.close();
conn.disconnect();
return in.toString();
}
} catch (Exception e) {
}
return null;
}
/**
* is转String
*
* @param in
* @return
* @throws IOException
*/
public static String inputStream2String(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
/**
* check net work
*
* @param context
* @return
*/
public static boolean hasNetwork(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo workinfo = con.getActiveNetworkInfo();
if (workinfo == null || !workinfo.isAvailable()) {
Toast.makeText(context, "当前无网络连接,请稍后重试", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/***
* @category check if the string is null
* @return true if is null
* */
public static boolean isNull(String string) {
boolean t1 = "".equals(string);
boolean t2 = string == null;
boolean t3 = string.equals("null");
if (t1 || t2 || t3) {
return true;
} else {
return false;
}
}
static public byte[] getBytes(File file) throws IOException {
InputStream ios = null;
ByteArrayOutputStream ous = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
public static class MLog {
static public void e(String msg) {
android.util.Log.e("=======ERROR======", msg);
}
static public void e(String tag, String msg) {
android.util.Log.e(tag, msg);
}
static public void i(String msg) {
android.util.Log.i("=======INFO======", msg);
}
static public void i(String tag, String msg) {
android.util.Log.i(tag, msg);
}
}
/**
* 处理https加密失败的情况
*
* @return
*/
public static HttpClient getNewHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new HttpUtil.SSLSocketFactoryEx(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
static public class SSLSocketFactoryEx extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public SSLSocketFactoryEx(KeyStore truststore)
throws NoSuchAlgorithmException, KeyManagementException,
KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType)
throws java.security.cert.CertificateException {
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port,
boolean autoClose) throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host,
port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
}
================2013 04 09 完全无其他依赖
package com.example.testbingtoken;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
/**
* HttpUtil Class Capsule Most Functions of Http Operations
*
* @author sfshine
*
*/
public class HttpUtil {
private static Header[] headers = new BasicHeader[1];
private static String TAG = "HTTPUTIL";
private static int TIMEOUT = 5 * 1000;
private static final String BOUNDARY = "---------------------------7db1c523809b2";
/**
* Your header of http op
*
* @return
*/
static {
headers[0] = new BasicHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
}
public static boolean delete(String murl) throws Exception {
URL url = new URL(murl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 204) {
MLog.e(conn.toString());
return true;
}
MLog.e(conn.getRequestMethod());
MLog.e(conn.getResponseCode() + "");
return false;
}
/**
* Op Http get request
*
* @param url
* @param map
* Values to request
* @return
*/
static public String get(String url) {
return get(url, null);
}
static public String get(String url, HashMap map) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
String result = "ERROR";
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
HttpGet get = new HttpGet(url);
get.setHeaders(headers);
Log.i(TAG, url);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// setCookie(response);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* Op Http post request , "404error" response if failed
*
* @param url
* @param map
* Values to request
* @return
*/
static public String post(String url, HashMap map) {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
HttpPost post = new HttpPost(url);
MLog.i(TAG, url);
post.setHeaders(headers);
String result = "ERROR";
ArrayList pairList = new ArrayList();
if (map != null) {
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
BasicNameValuePair pair = new BasicNameValuePair(
entry.getKey(), entry.getValue());
pairList.add(pair);
}
}
try {
HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* 自定义的http请求可以设置为DELETE PUT等而不是GET
*
* @param url
* @param params
* @param method
* @throws IOException
*/
public static String customrequest(String url,
HashMap params, String method) {
try {
URL postUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) postUrl
.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod(method);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
conn.connect();
OutputStream out = conn.getOutputStream();
StringBuilder sb = new StringBuilder();
if (null != params) {
int i = params.size();
for (Map.Entry entry : params.entrySet()) {
if (i == 1) {
sb.append(entry.getKey() + "=" + entry.getValue());
} else {
sb.append(entry.getKey() + "=" + entry.getValue() + "&");
}
i--;
}
}
String content = sb.toString();
out.write(content.getBytes("UTF-8"));
out.flush();
out.close();
InputStream inStream = conn.getInputStream();
String result = inputStream2String(inStream);
Log.i(TAG, "result>" + result);
conn.disconnect();
return result;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* 必须严格限制get请求所以增加这个方法 这个方法也可以自定义请求
*
* @param url
* @param method
* @throws Exception
*/
public static String customrequestget(String url,
HashMap map, String method) {
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
try {
URL murl = new URL(url);
System.out.print(url);
HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod(method);
conn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
InputStream inStream = conn.getInputStream();
String result = inputStream2String(inStream);
Log.i(TAG, "result>" + result);
conn.disconnect();
return result;
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* 上传多张图片
*/
public static void post(String actionUrl, Map params,
Map files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(
conn.getOutputStream());
outStream.write(sb.toString().getBytes());
InputStream in = null;
// 发送文件数据
if (files != null) {
for (Map.Entry file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"source\"; filename=\""
+ file.getValue().getName() + "\"" + LINEND);
sb1.append("Content-Type: image/pjpeg; " + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
// if (res == 200) {
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
// }
outStream.close();
conn.disconnect();
}
// return in.toString();
}
/**
* is转String
*
* @param in
* @return
* @throws IOException
*/
public static String inputStream2String(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
/**
* check net work
*
* @param context
* @return
*/
public static boolean hasNetwork(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo workinfo = con.getActiveNetworkInfo();
if (workinfo == null || !workinfo.isAvailable()) {
Toast.makeText(context, "当前无网络连接,请稍后重试", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/***
* @category check if the string is null
* @return true if is null
* */
public static boolean isNull(String string) {
boolean t1 = "".equals(string);
boolean t2 = string == null;
boolean t3 = string.equals("null");
if (t1 || t2 || t3) {
return true;
} else {
return false;
}
}
static public byte[] getBytes(File file) throws IOException {
InputStream ios = null;
ByteArrayOutputStream ous = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
public static class MLog {
static public void e(String msg) {
android.util.Log.e("=======ERROR======", msg);
}
static public void e(String tag, String msg) {
android.util.Log.e(tag, msg);
}
static public void i(String msg) {
android.util.Log.i("=======INFO======", msg);
}
static public void i(String tag, String msg) {
android.util.Log.i(tag, msg);
}
}
}
package com.su.doubanrise.util;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
import com.su.doubanrise.api.Douban;
import com.su.doubanrise.api.bean.FormFile;
/**
* HttpUtil Class Capsule Most Functions of Http Operations
*
* @author sfshine
*
*/
public class HttpUtil {
private static Header[] headers = new BasicHeader[11];
private static String TAG = "HTTPUTIL";
private static int TIMEOUT = 5 * 1000;
private static final String BOUNDARY = "---------------------------7db1c523809b2";
/**
* Your header of http op
*/
static {
headers[0] = new BasicHeader("Authorization", "Bearer "
+ Douban.getAccessToken());
headers[1] = new BasicHeader("Udid", "");
headers[2] = new BasicHeader("Os", "");
headers[3] = new BasicHeader("Osversion", "");
headers[4] = new BasicHeader("Appversion", "");
headers[5] = new BasicHeader("Sourceid", "");
headers[6] = new BasicHeader("Ver", "");
headers[7] = new BasicHeader("Userid", "");
headers[8] = new BasicHeader("Usersession", "");
headers[9] = new BasicHeader("Unique", "");
headers[10] = new BasicHeader("Cookie", "");
}
public static boolean delete(String murl) throws Exception {
URL url = new URL(murl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 204) {
MLog.e(conn.toString());
return true;
}
MLog.e(conn.getRequestMethod());
MLog.e(conn.getResponseCode() + "");
return false;
}
/**
* Op Http get request
*
* @param url
* @param map
* Values to request
* @return
*/
static public String get(String url) {
return get(url, null);
}
static public String get(String url, HashMap map) {
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
MLog.e(headers[0] + "");
String result = "ERROR";
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
HttpGet get = new HttpGet(url);
get.setHeaders(headers);
Log.i(TAG, url);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// setCookie(response);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* 上传带图片的http请求
*
* @param murl网址
* @param map
* 参数对 主要不要包括图片
* @param path
* 图片路径 也可以是其他格式 自行做
* @return
* @throws Exception
*/
static public String post(String murl, HashMap map,
String path) throws Exception {
File file = new File(path);
String filename = path.substring(path.lastIndexOf("/"));
// String filename = Str.md5(path);
StringBuilder sb = new StringBuilder();
if (null != map) {
for (Map.Entry entry : map.entrySet()) {
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + "\r\n");
sb.append("\r\n");
sb.append(entry.getValue() + "\r\n");
}
}
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"image\"; filename=\""
+ filename + "\"" + "\r\n");
sb.append("Content-Type: image/pjpeg" + "\r\n");
sb.append("\r\n");
byte[] before = sb.toString().getBytes("UTF-8");
byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL(murl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Authorization",
"Bearer " + Douban.getAccessToken());
conn.setRequestProperty("Content-Length",
String.valueOf(before.length + file.length() + after.length));
conn.setRequestProperty("HOST", url.getHost());
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(file);
out.write(before);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(after);
in.close();
out.close();
MLog.i("result=>" + inputStream2String(conn.getInputStream()) + "");
if (conn.getResponseCode() == HttpStatus.SC_OK) {
return inputStream2String(conn.getInputStream());
} else {
return inputStream2String(conn.getInputStream()) + "Code"
+ conn.getResponseCode();
}
}
/**
* is转String
*
* @param in
* @return
* @throws IOException
*/
public static String inputStream2String(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
/**
* Op Http post request , "404error" response if failed
*
* @param url
* @param map
* Values to request
* @return
*/
static public String post(String url, HashMap map) {
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
HttpPost post = new HttpPost(url);
Log.i(TAG, url);
MLog.e(headers[0] + "");
post.setHeaders(headers);
String result = "ERROR";
ArrayList pairList = new ArrayList();
if (map != null) {
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
BasicNameValuePair pair = new BasicNameValuePair(
entry.getKey(), entry.getValue());
pairList.add(pair);
}
}
try {
HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* Post Bytes to Server
*
* @param url
* @param bytes
* of text
* @return
*/
public static String PostBytes(String url, byte[] bytes) {
try {
URL murl = new URL(url);
final HttpURLConnection con = (HttpURLConnection) murl
.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "text/html");
String cookie = headers[10].getValue();
if (!isNull(headers[10].getValue())) {
con.setRequestProperty("cookie", cookie);
}
con.setReadTimeout(TIMEOUT);
con.setConnectTimeout(TIMEOUT);
Log.i(TAG, url);
DataOutputStream dsDataOutputStream = new DataOutputStream(
con.getOutputStream());
dsDataOutputStream.write(bytes, 0, bytes.length);
dsDataOutputStream.close();
if (con.getResponseCode() == HttpStatus.SC_OK) {
InputStream isInputStream = con.getInputStream();
int ch;
StringBuffer buffer = new StringBuffer();
while ((ch = isInputStream.read()) != -1) {
buffer.append((char) ch);
}
Log.i(TAG, "GetDataFromServer>" + buffer.toString());
return buffer.toString();
} else {
return "404error";
}
} catch (SocketTimeoutException e) {
return "timeouterror";
} catch (IOException e) {
// TODO Auto-generated catch block
return "404error";
}
}
/**
* set Cookie
*
* @param response
*/
private static void setCookie(HttpResponse response) {
if (response.getHeaders("Set-Cookie").length > 0) {
Log.d(TAG, response.getHeaders("Set-Cookie")[0].getValue());
headers[10] = new BasicHeader("Cookie",
response.getHeaders("Set-Cookie")[0].getValue());
}
}
/**
* check net work
*
* @param context
* @return
*/
public static boolean hasNetwork(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo workinfo = con.getActiveNetworkInfo();
if (workinfo == null || !workinfo.isAvailable()) {
Toast.makeText(context, "当前无网络连接,请稍后重试", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/***
* @category check if the string is null
* @return true if is null
* */
public static boolean isNull(String string) {
boolean t1 = "".equals(string);
boolean t2 = string == null;
boolean t3 = string.equals("null");
if (t1 || t2 || t3) {
return true;
} else {
return false;
}
}
}
2012 12 31 添加自定义的URLConnection请求版本
package com.su.doubanrise.util;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
import com.su.doubanrise.api.Douban;
import com.su.doubanrise.api.bean.FormFile;
/**
* HttpUtil Class Capsule Most Functions of Http Operations
*
* @author sfshine
*
*/
public class HttpUtil {
private static Header[] headers = new BasicHeader[11];
private static String TAG = "HTTPUTIL";
private static int TIMEOUT = 5 * 1000;
private static final String BOUNDARY = "---------------------------7db1c523809b2";
/**
* 在第一次授权的时候可能头部是空需要调用这个方法初始化token
*/
public static void initAfterAuth() {
headers[0] = new BasicHeader("Authorization", "Bearer "
+ Douban.getAccessToken());
}
/**
* Your header of http op
*
* @return
*/
static {
headers[0] = new BasicHeader("Authorization", "Bearer "
+ Douban.getAccessToken());
// headers[0] = new BasicHeader("Authorization",
// Douban.getAccessToken());
headers[1] = new BasicHeader("Udid", "");
headers[2] = new BasicHeader("Os", "");
headers[3] = new BasicHeader("Osversion", "");
headers[4] = new BasicHeader("Appversion", "");
headers[5] = new BasicHeader("Sourceid", "");
headers[6] = new BasicHeader("Ver", "");
headers[7] = new BasicHeader("Userid", "");
headers[8] = new BasicHeader("Usersession", "");
headers[9] = new BasicHeader("Unique", "");
headers[10] = new BasicHeader("Cookie", "");
}
public static boolean delete(String murl) throws Exception {
URL url = new URL(murl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("DELETE");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 204) {
MLog.e(conn.toString());
return true;
}
MLog.e(conn.getRequestMethod());
MLog.e(conn.getResponseCode() + "");
return false;
}
/**
* Op Http get request
*
* @param url
* @param map
* Values to request
* @return
*/
static public String get(String url) {
return get(url, null);
}
static public String get(String url, HashMap map) {
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
MLog.e(headers[0] + "");
String result = "ERROR";
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
HttpGet get = new HttpGet(url);
get.setHeaders(headers);
Log.i(TAG, url);
try {
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// setCookie(response);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* 上传带图片的http请求
*
* @param murl网址
* @param map
* 参数对 主要不要包括图片
* @param path
* 图片路径 也可以是其他格式 自行做
* @return
* @throws Exception
*/
static public String post(String murl, HashMap map,
String path) throws Exception {
File file = new File(path);
String filename = path.substring(path.lastIndexOf("/"));
// String filename = Str.md5(path);
StringBuilder sb = new StringBuilder();
if (null != map) {
for (Map.Entry entry : map.entrySet()) {
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + "\r\n");
sb.append("\r\n");
sb.append(entry.getValue() + "\r\n");
}
}
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"image\"; filename=\""
+ filename + "\"" + "\r\n");
sb.append("Content-Type: image/pjpeg" + "\r\n");
sb.append("\r\n");
byte[] before = sb.toString().getBytes("UTF-8");
byte[] after = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL(murl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("Authorization",
"Bearer " + Douban.getAccessToken());
conn.setRequestProperty("Content-Length",
String.valueOf(before.length + file.length() + after.length));
conn.setRequestProperty("HOST", url.getHost());
conn.setDoOutput(true);
OutputStream out = conn.getOutputStream();
InputStream in = new FileInputStream(file);
out.write(before);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) != -1)
out.write(buf, 0, len);
out.write(after);
in.close();
out.close();
MLog.i("result=>" + inputStream2String(conn.getInputStream()) + "");
if (conn.getResponseCode() == HttpStatus.SC_OK) {
return inputStream2String(conn.getInputStream());
} else {
return inputStream2String(conn.getInputStream()) + "Code"
+ conn.getResponseCode();
}
}
/**
* is转String
*
* @param in
* @return
* @throws IOException
*/
public static String inputStream2String(InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
/**
* Op Http post request , "404error" response if failed
*
* @param url
* @param map
* Values to request
* @return
*/
static public String post(String url, HashMap map) {
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT);
HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT);
ConnManagerParams.setTimeout(client.getParams(), TIMEOUT);
HttpPost post = new HttpPost(url);
Log.i(TAG, url);
MLog.e(headers[0] + "");
post.setHeaders(headers);
String result = "ERROR";
ArrayList pairList = new ArrayList();
if (map != null) {
for (Map.Entry entry : map.entrySet()) {
Log.i(TAG, entry.getKey() + "=>" + entry.getValue());
BasicNameValuePair pair = new BasicNameValuePair(
entry.getKey(), entry.getValue());
pairList.add(pair);
}
}
try {
HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8");
post.setEntity(entity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} else {
result = EntityUtils.toString(response.getEntity(), "UTF-8")
+ response.getStatusLine().getStatusCode() + "ERROR";
}
} catch (ConnectTimeoutException e) {
result = "TIMEOUTERROR";
}
catch (Exception e) {
result = "OTHERERROR";
e.printStackTrace();
}
Log.i(TAG, "result =>" + result);
return result;
}
/**
* 自定义的http请求可以设置为DELETE PUT等而不是GET
*
* @param url
* @param params
* @param method
* @throws IOException
*/
public static void customrequest(String url,
HashMap params, String method) throws IOException {
URL postUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(5 * 1000);
conn.setRequestProperty("Authorization",
"Bearer " + Douban.getAccessToken());
conn.setRequestMethod(method);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
OutputStream out = conn.getOutputStream();
StringBuilder sb = new StringBuilder();
if (null != params) {
int i = params.size();
for (Map.Entry entry : params.entrySet()) {
if (i == 1) {
sb.append(entry.getKey() + "=" + entry.getValue());
} else {
sb.append(entry.getKey() + "=" + entry.getValue() + "&");
}
i--;
}
}
String content = sb.toString();
System.out.print(content);
out.write(content.getBytes("UTF-8"));
out.flush();
out.close();
InputStream inStream = conn.getInputStream();
String result = inputStream2String(inStream);
System.out.println(result);
conn.disconnect();
}
/**
* 豆瓣必须严格限制get请求所以增加这个方法 这个方法也可以自定义请求
*
* @param url
* @param method
* @throws Exception
*/
public static void customrequestget(String url,
HashMap map, String method) throws Exception {
if (null != map) {
int i = 0;
for (Map.Entry entry : map.entrySet()) {
if (i == 0) {
url = url + "?" + entry.getKey() + "=" + entry.getValue();
} else {
url = url + "&" + entry.getKey() + "=" + entry.getValue();
}
i++;
}
}
URL murl = new URL(url);
System.out.print(url);
HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization",
"Bearer " + Douban.getAccessToken());
InputStream inStream = conn.getInputStream();
String result = inputStream2String(inStream);
System.out.println(result);
conn.disconnect();
}
/**
* Post Bytes to Server
*
* @param url
* @param bytes
* of text
* @return
*/
public static String PostBytes(String url, byte[] bytes) {
try {
URL murl = new URL(url);
final HttpURLConnection con = (HttpURLConnection) murl
.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "text/html");
String cookie = headers[10].getValue();
if (!isNull(headers[10].getValue())) {
con.setRequestProperty("cookie", cookie);
}
con.setReadTimeout(TIMEOUT);
con.setConnectTimeout(TIMEOUT);
Log.i(TAG, url);
DataOutputStream dsDataOutputStream = new DataOutputStream(
con.getOutputStream());
dsDataOutputStream.write(bytes, 0, bytes.length);
dsDataOutputStream.close();
if (con.getResponseCode() == HttpStatus.SC_OK) {
InputStream isInputStream = con.getInputStream();
int ch;
StringBuffer buffer = new StringBuffer();
while ((ch = isInputStream.read()) != -1) {
buffer.append((char) ch);
}
Log.i(TAG, "GetDataFromServer>" + buffer.toString());
return buffer.toString();
} else {
return "404error";
}
} catch (SocketTimeoutException e) {
return "timeouterror";
} catch (IOException e) {
// TODO Auto-generated catch block
return "404error";
}
}
/**
* set Cookie
*
* @param response
*/
private static void setCookie(HttpResponse response) {
if (response.getHeaders("Set-Cookie").length > 0) {
Log.d(TAG, response.getHeaders("Set-Cookie")[0].getValue());
headers[10] = new BasicHeader("Cookie",
response.getHeaders("Set-Cookie")[0].getValue());
}
}
/**
* check net work
*
* @param context
* @return
*/
public static boolean hasNetwork(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo workinfo = con.getActiveNetworkInfo();
if (workinfo == null || !workinfo.isAvailable()) {
Toast.makeText(context, "当前无网络连接,请稍后重试", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/***
* @category check if the string is null
* @return true if is null
* */
public static boolean isNull(String string) {
boolean t1 = "".equals(string);
boolean t2 = string == null;
boolean t3 = string.equals("null");
if (t1 || t2 || t3) {
return true;
} else {
return false;
}
}
}
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
android http封装类,HTTP封装类 工具类 For Android相关推荐
- Android开发 无线Wifi+WifiUtil工具类,android开发网格布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=&quo ...
- android隐藏键盘方法,【工具类】Android 最有效的隐藏软键盘方法
前言 在平时的 App 开发中, 免不了会遇到需要开发者隐藏软键盘的情况, 比如当在多个输入框填入个人基本信息, 最后有个保存按钮, 点击即可将个人基本信息保存, 这时就需要开发者编写代码去隐藏软键盘 ...
- android开发监听媒体播放器,Android开发之媒体播放工具类完整示例
本文实例讲述了Android开发之媒体播放工具类.分享给大家供大家参考,具体如下: package com.maobang.imsdk.util; import android.media.Media ...
- Android开发 几个常用工具类
本文出自[张鸿洋的博客]并 做了部分修改. 转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311 打开大家手上的项目,基 ...
- Android之SharedPreferences两个工具类
相信Android的这个最简单的存储方式大家都很熟悉了,但是有一个小小技巧,也许你没有用过,今天就跟大家分享一下,我们可以把SharedPreferences封装在一个工具类中,当我们需要写数据和读数 ...
- Android中调用webservice的工具类
最近学习WebService,感觉利用这个借口开发网站的Android客户端方便及了,用到一个工具类,这里铭记一下. public static final String WebServiceName ...
- android okhttp+解析json( okhttp 工具类)
2019.12.28更新 注意点: 1.只需要在AndroidManifest.xml application 属性中添加 ,就可以访问 http,而不是https android:usesClear ...
- 一个简单易用的Http访问工具类for Android
前言 去年(2017)参加服务外包省赛的时候,负责App开发的我遇到了一个小难题--Http请求.虽说已经有成熟的HttpUrlConnection库供使用,但依然感到有些不方便:进行一次简单的请求并 ...
- Android RSA加密解密的 工具类的使用
RSA 比较特殊,我们首先要生成私钥和公钥,然后在加密的时候,使用私钥加密,在解密的时候使用公钥解密. //RSA 的初始化,获得私钥和密钥public void rsaInit(){try {Key ...
- Android开发:手机震动工具类
新思路,如果你在做关于通知Notification方便的工作,在涉及到多种通知方式组合时(例如:铃声.轻震动.强震动等),感觉到系统提供的API比较吃力的话,建议可以自己来实现通知效果,根据开发经验, ...
最新文章
- win10下安装TensorFlow(CPU only)
- python自定义函数和类并调用
- pom.xml中的常用依赖包总结
- BeautifulSoup总结
- 卷积神经网络(CNN)小结
- 分布式调用时(WCF?)慎用 using(xxx){}
- 按功能而不是按层打包课程
- (三)Neo4j自带northwind案例--Cypher语言应用
- 腾讯被迫下架《怪物猎人世界》;传谷歌将支持 Win10 ;苹果或将复活 MagSafe | 极客头条...
- eclipse快捷键_Eclipse快捷键
- 索尼z5原生android6.0,索尼Z5怎么刷安卓6.0?索尼Z5刷安卓6.0固件包教程
- Android 利用高德地图API进行定位、开发电子围栏、天气预报、轨迹记录、搜索周边(位置)
- FATE联邦学习初探(二)
- 微软teams软件_如何在Microsoft Teams中创建和管理团队
- 传奇人物张三的爱情困境
- ansj分词器的配置
- JavaEE框架类——监听器(观察者模式)和Servlet技术的监听器session沌化与活化技术
- 如何监测内存泄漏(引用自网络)
- kafka:过期数据清理
- bms测试软件,BMS测试设备
热门文章
- 淘宝电影“追杀”猫眼电影,同门相争不可避免
- java类加载机制ClassLoad
- 【转载】VC遍历文件夹下所有文件和文件夹
- 给出如下公式的python表达式7+9i+2xcos66_这100道练习,带你玩转Numpy
- python抽取指定url页面的title_Python新手写爬虫全过程记录分析
- 基于python的气象数据分析_基于python的《Hadoop权威指南》一书中气象数据下载和map reduce化数据处理及其......
- 相对于其他框架的离子应用开发:它被炒作了吗?
- 分步傅里叶算法_分布傅里叶算法求解非线性薛定谔的matlab程序问题
- 基于 Windows 7 的计算机可用内存低于安装内存
- Halcon 例程学习之频域自相关变换( correlation_fft)