package com.express.express.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
public class HttpHelper {
/**
* 利用android 下载管理器 下载文件
*
* @param context
* @param apkName
* @param uri
* http或https
* @return 如果已经下载过返回-1,否则返回Download ID
*/
public static long download(Context context, String apkName, Uri uri) {
File dir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File apkFile = new File(dir, apkName);
if (apkFile.exists()) {
ApplicationHelper.installApk(context, Uri.fromFile(apkFile));
return -1;
}
Toast.makeText(context, "已经转入后台下载!", Toast.LENGTH_SHORT).show();
DownloadManager manager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE); // 初始化下载管理器
DownloadManager.Request request = new DownloadManager.Request(uri);// 创建请求
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_WIFI);// 设置允许使用的网络类型,这里是移动网络和wifi都可以
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setAllowedOverRoaming(false);// 漫游
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, apkName);
Log.v("Download", "Download DIR:+" + Environment.DIRECTORY_DOWNLOADS);
long id = manager.enqueue(request);
SharedPreferences sp = context.getSharedPreferences(Constant.SP_USER,
Context.MODE_PRIVATE);
sp.edit().putLong(Constant.DOWNLOAD_ID, id).commit();
return id;// 将下载请求放入队列
}
/**
* http POST 请求
*
* @param url
* http请求
* @param content
* 请求正文,正文内容其实跟get的URL中'?'后的参数字符串一致
* @return
* @throws IOException
*/
public static String requestPost(String urlString, String content)
throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000);
// Read from the connection. Default is true.
conn.setDoInput(true);
// Output to the connection. Default is
// false, set to true because post
// method must write something to the
// connection
// 设置是否向connection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true
conn.setDoOutput(true);
// Post cannot use caches
conn.setUseCaches(false);
// Set the post method. Default is GET
conn.setRequestMethod("POST");
// This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
// This methods only
// takes effacts to this
// instance.
conn.setInstanceFollowRedirects(true);
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
// 进行编码
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
// 要注意的是connection.getOutputStream会隐含的进行connect。
conn.connect();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
// The URL-encoded contend
// DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
out.writeBytes(content);
out.flush();
out.close(); // flush and close
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
conn.disconnect();
return sb.toString();
}
/**
* http Post请求 ,参考 {@link #requestPost(String,String)
* requestPost(String,String)}
*
* @param urlString
* 请求url
* @param map
* 封装了正文内容的map
* @return
* @throws IOException
*
*/
public static String requestPost(String urlString, Map<String, String> map)
throws IOException {
// 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
// String content =
// "key=j0r53nmbbd78x7m1pqml06u2&type=1&toemail=cngolon@gmail.com"
// + "&activatecode=" + URLEncoder.encode("中国聚龙", "utf-8");
String content = "";
for (Entry<String, String> en : map.entrySet()) {
String key = en.getKey();
String value = URLEncoder.encode(en.getValue(), "utf-8");
if (!"".equals(content)) {
content += "&";
}
content += key + "=" + value;
}
return requestPost(urlString, content);
}
/**
* http GET 请求
*
* @param url
* @return
* @throws IOException
*/
public static String requestGet(String url) throws IOException {
URL getUrl = new URL(url);
// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
connection.setConnectTimeout(6 * 1000);
// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
// 服务器
connection.connect();
// 取得输入流,并使用Reader读取
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
String line;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
// 断开连接
connection.disconnect();
return sb.toString();
}
/**
* 读取图片
* @param url 图片url
* @return Bitmap
* @throws IOException
*/
public static Bitmap getBitmap(String url) throws IOException {
// 获得连接
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
// 设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制
conn.setConnectTimeout(6000);
// 连接设置获得数据流
conn.setDoInput(true);
// 不使用缓存
conn.setUseCaches(false);
// 这句可有可无,没有影响
conn.connect();
// 得到数据流
InputStream is = conn.getInputStream();
// 解析得到图片
Bitmap bitMap = BitmapFactory.decodeStream(is);
is.close();
return bitMap;
}
}
android http 辅助类
最新推荐文章于 2024-01-31 16:02:39 发布