Summary of methods I often use to interact with servers (part I)
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; impor T 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; I Mport 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 {/*** send a get request to the specified url ** @ param url * request url * @ param params * request parameter format name1 = value1 & name2 = value2 * @ return response resource */public static String sendGet (String url, string params) {String result = ""; BufferedReader in = null; try {String urlName = url + "? "+ Params; URL realUrl = new URL (urlName); // enable the url Connection URLConnection conn = realUrl. openConnection (); // set the common request attribute conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setRequestProperty ("user-agent", "ILA ila/4.0 (Compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // establish a connection conn. connect (); // defines the BuffereReader input and output stream to read the URL response 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 the specified url address * @ param paras parameter format is 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 {// send the request HttpResponse httpResponse=httpClient.exe cute (httpGet); if (httpRe Else se. getStatusLine (). getStatusCode () = 200) {result = EntityUtils. toString (httpResponse. getEntity ();} else {result = "No Server Response";} catch (Exception e) {e. printStackTrace ();} return result ;} /*** send a get request to a specified url ** @ param url * request url * @ param params * request parameter format name1 = value1 & name2 = value2 * @ return response resource */public static String sendPost1 (String url, string params) {String result = ""; PrintWriter out = null; Buffer EdReader in = null; try {URL realUrl = new URL (url); // link between opening and URL URLConnection conn = realUrl. openConnection (); // set the common request parameter conn. setRequestProperty ("accept", "*/*"); conn. setRequestProperty ("connection", "Keep-Alive"); conn. setRequestProperty ("user-agent", "ILA ila/4.0 (Compatible; MSIE 6.0; Windows NT 5.1; SV1)"); // The following two rows of conn must be set to send a Post request. setDoInput (true); conn. setDoOutput (true); // get the output stream of the URLconnection object out = New PrintWriter (conn. getOutputStream (); // sends the request parameter out. print (params); // flush the Buffer out of the output stream. flush (); // defines the BuffereReader input stream to read the URL response 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 ;} /*** send Post request *** @ param url * request address * @ param paras * The request parameter is different from sendPost2 in the form of a post key-Value Pair * @ return server response result */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 httpresponeappshttpclient.exe cute (httpPost); if (httpRespone. getStatusLine (). getStatusCode () = 200) {result = EntityUtils. toString (httpRespone. getEntity ();} else {result = "the server has no response! ";}} Catch (UnsupportedEncodingException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} return result;}/***** @ param scr promotion image address * @ 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 ;} /*** get the size of the byte stream array of the image ** @ param inStream * @ return * @ throws Exception */public static byte [] readStream (Indium UtStream 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 ();}/*** check version updates ** @ param context * @ param hander * @ param scr ** @ return */public static Boolean u PdateVersion (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 ("unable to know the file size on the 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; // download msg. obj = downFileSize; OS. write (bytes, 0, hascode);} // download complete 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 {/*** network connection status ** @ param context * Context * @ return indicates whether the network is connected to true. If this parameter is set to "false", the network cannot be connected. */public static boolean getNetWorkStatus (context) {ConnectivityManager manger = (ConnectivityManager) context. getSystemService (Context. CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manger. getActiveNetworkInfo (); if (networkInfo = null) {return false;} return true ;} /*** get local phone number ** @ param context * Context * @ return local phone number */public static String getTeleNumber (context) {TelephonyManager telephoneManger = (TelephonyManager) context. getSystemService (Context. TELEPHONY_SERVICE); return telephoneManger. getLine1Number ();}/*** whether sdcard can be read and written ** @ 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 * Context * @ return true or false */public static boolean isCanUseSim (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 returns the current version number */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 ;}}