Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android之UtilsRequesServicetHelp工具類

Android之UtilsRequesServicetHelp工具類

編輯:關於Android編程

本人經常與服務器交互用到的方法總結(部分)

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="服務器無響應";
			}
		}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 服務器響應結果
	 */
	public static String sendPost2(String url, List 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= "服務器無響應!";
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}catch(Exception e){
			e.printStackTrace();
		}
		return result;
	}



	/**
	 * 
	 * @param scr推廣圖片地址
	 * @return
	 */
	public static List getUrlImage(List scr) {
		List bitmap = new ArrayList();
		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("無法獲知服務器上文件的大小");
			}
			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;
	}
}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved