package com.example.getnetutil;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
public class UtilGetPost {
/**
* 向指定的url发送get请求
*
* @param url
* 请求的url
* @param params
* 请求參数 格式 name1=value1&name2=value2
* @return 响应的资源
*/
public static String sendGet(String url, String params) {
String result = "";
BufferedReader in = null;
try {
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打开和url之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozila/4.0(Compatible;MSIE 6.0;Windows NT 5.1;SV1)");
// 建立连接
conn.connect();
// 定义BuffereReader输入输出流来读取URL响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
/**
*
* @param url指定的url地址
* @param paras參数格式为 name=value&name1=value1
* @return
*/
public static String sendGet1(String url,String paras){
String result="";
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet(url+paras);
try{
//发送请求
HttpResponse httpResponse=httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode()==200){
result=EntityUtils.toString(httpResponse.getEntity());
}else{
result="server无响应";
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
* 向指定的url发送get请求
*
* @param url
* 请求的url
* @param params
* 请求參数 格式 name1=value1&name2=value2
* @return 响应的资源
*/
public static String sendPost1(String url, String params) {
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的联系
URLConnection conn = realUrl.openConnection();
// 设置通用的请求參数
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozila/4.0(Compatible;MSIE 6.0;Windows NT 5.1;SV1)");
// 发送Post请求必须设置例如以下两行
conn.setDoInput(true);
conn.setDoOutput(true);
// 获取URLconnection对象的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求參数
out.print(params);
// flush输出流的缓冲
out.flush();
// 定义BuffereReader输入流来读取URL响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
/**
* 发送Post请求
*
* @param url
* 请求的地址
* @param paras
* 请求的參数 和sendPost2不同的是这个是post键值对形式
* @return server响应结果
*/
public static String sendPost2(String url, List<NameValuePair> paras) {
String result = "";
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(paras, HTTP.UTF_8));
HttpResponse httpRespone=httpClient.execute(httpPost);
if(httpRespone.getStatusLine().getStatusCode()==200){
result=EntityUtils.toString(httpRespone.getEntity());
}else{
result= "server无响应。";
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return result;
}
/**
*
* @param scr推广图片地址
* @return
*/
public static List<Bitmap> getUrlImage(List<String> scr) {
List<Bitmap> bitmap = new ArrayList<Bitmap>();
try {
for (int i = 0; i < scr.size(); i++) {
URL url = new URL(scr.get(i));
InputStream is = url.openStream();
if (is != null) {
byte[] data = readStream(is);
if (data != null) {
Bitmap bt = BitmapFactory.decodeByteArray(data, 0,
data.length);
bitmap.add(bt);
}
}
// Bitmap bt = BitmapFactory.decodeStream(is);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 得到图片字节流 数组大小
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inStream.read(buffer)) >0) {
outStream.write(buffer, 0, len);
outStream.flush();
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
/**
* 检查版本号更新
*
* @param context
* @param hander
* @param scr
* 下载地址
* @return
*/
public static Boolean updateVersion(Context context, Handler hander,
String scr) {
String filePath = "";
int downFileSize = 0;
Message msg = new Message();
String fileName = scr.substring(scr.lastIndexOf("/") + 1);
try {
URL url = new URL(scr);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(10000);
conn.connect();
int fileSize = conn.getContentLength();
InputStream is = conn.getInputStream();
FileOutputStream os = null;
if (fileSize <= 0) {
throw new RuntimeException("无法获知server上文件的大小");
}
if (is == null) {
throw new RuntimeException("stream is null");
}
if (LocalPhoneStatus.IsCanUseSdCard()) {
filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/niwodai/";
if (!new File(filePath).exists()) {
new File(filePath).mkdirs();
}
filePath = filePath + "/" + fileName;
if (new File(filePath).exists()) {
new File(filePath).delete();
}
File file = new File(filePath);
file.createNewFile();
os = new FileOutputStream(file);
} else {
os = context.openFileOutput("BkClient.apk",
Context.MODE_PRIVATE + Context.MODE_WORLD_READABLE);
}
byte[] bytes = new byte[1024];
int hascode = 0;
msg.what = 0X123;
while ((hascode = is.read(bytes)) > 0) {
hander.sendMessage(msg);
downFileSize = +hascode;
// 正在下载
msg.obj = downFileSize;
os.write(bytes, 0, hascode);
}
// 下载完毕
msg.what = 0X234;
hander.sendMessage(msg);
os.flush();
os.close();
is.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (LocalPhoneStatus.IsCanUseSdCard()) {
intent.setDataAndType(Uri.parse("file://"
+ Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/niwodai/Client.apk"),
"application/vnd.android.package-archive");
} else {
File f = new File(context.getFilesDir().getPath() + "/Client.apk");
intent.setDataAndType(Uri.fromFile(f),
"application/vnd.android.package-archive");
}
context.startActivity(intent);
return true;
}
}
class LocalPhoneStatus {
/**
* 网络连接状态
*
* @param context
* 上下文
* @return 网络是否连接 true为可连接 false为不可连接
*/
public static boolean getNetWorkStatus(Context context) {
ConnectivityManager manger = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manger.getActiveNetworkInfo();
if (networkInfo == null) {
return false;
}
return true;
}
/**
* 获取本机电话号码
*
* @param context
* 上下文
* @return 本机电话号码
*/
public static String getTeleNumber(Context context) {
TelephonyManager telephoneManger = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return telephoneManger.getLine1Number();
}
/**
* sdcard是否可读写
*
* @return ture or false
*/
public static boolean IsCanUseSdCard() {
try {
return Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
*
* @param context
* 上下文
* @return ture or false
*/
public static boolean isCanUseSim(Context context) {
try {
TelephonyManager mgr = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
return TelephonyManager.SIM_STATE_READY == mgr.getSimState();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
*
* @param context
* @return 返回当前的版本号号
*/
public static String getVersion(Context context) {
PackageManager pagePackageManager = context.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = pagePackageManager.getPackageInfo(
context.getPackageName(), 0);
String version = packageInfo.versionName;
return version;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
浙公网安备 33010602011771号