转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38965311,本文出自【张鸿洋的博客】
打开大家手上的项目,基本都会有一大批的辅助类,今天特此整理出10个基本每个项目中都会使用的工具类,用于快速开发~~
在此感谢群里给我发项目中工具类的兄弟/姐妹~
1、日志工具类L.java- packagecom.zhy.utils;
- importandroid.util.Log;
- /**
- *Log统一管理类
- *
- *
- *
- */
- publicclassL
- {
- privateL()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- publicstaticbooleanisDebug=true;//是否需要打印bug,可以在application的onCreate函数里面初始化
- privatestaticfinalStringTAG="way";
- //下面四个是默认tag的函数
- publicstaticvoidi(Stringmsg)
- {
- if(isDebug)
- Log.i(TAG,msg);
- }
- publicstaticvoidd(Stringmsg)
- {
- if(isDebug)
- Log.d(TAG,msg);
- }
- publicstaticvoide(Stringmsg)
- {
- if(isDebug)
- Log.e(TAG,msg);
- }
- publicstaticvoidv(Stringmsg)
- {
- if(isDebug)
- Log.v(TAG,msg);
- }
- //下面是传入自定义tag的函数
- publicstaticvoidi(Stringtag,Stringmsg)
- {
- if(isDebug)
- Log.i(tag,msg);
- }
- publicstaticvoidd(Stringtag,Stringmsg)
- {
- if(isDebug)
- Log.i(tag,msg);
- }
- publicstaticvoide(Stringtag,Stringmsg)
- {
- if(isDebug)
- Log.i(tag,msg);
- }
- publicstaticvoidv(Stringtag,Stringmsg)
- {
- if(isDebug)
- Log.i(tag,msg);
- }
- }
网上看到的类,注释上应该原创作者的名字,很简单的一个类;网上也有很多提供把日志记录到SDCard上的,不过我是从来没记录过,所以引入个最简单的,大家可以进行评价是否需要扩充~~
2、Toast统一管理类- packagecom.zhy.utils;
- importandroid.content.Context;
- importandroid.widget.Toast;
- /**
- *Toast统一管理类
- *
- */
- publicclassT
- {
- privateT()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- publicstaticbooleanisShow=true;
- /**
- *短时间显示Toast
- *
- *@paramcontext
- *@parammessage
- */
- publicstaticvoidshowShort(Contextcontext,CharSequencemessage)
- {
- if(isShow)
- Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
- }
- /**
- *短时间显示Toast
- *
- *@paramcontext
- *@parammessage
- */
- publicstaticvoidshowShort(Contextcontext,intmessage)
- {
- if(isShow)
- Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
- }
- /**
- *长时间显示Toast
- *
- *@paramcontext
- *@parammessage
- */
- publicstaticvoidshowLong(Contextcontext,CharSequencemessage)
- {
- if(isShow)
- Toast.makeText(context,message,Toast.LENGTH_LONG).show();
- }
- /**
- *长时间显示Toast
- *
- *@paramcontext
- *@parammessage
- */
- publicstaticvoidshowLong(Contextcontext,intmessage)
- {
- if(isShow)
- Toast.makeText(context,message,Toast.LENGTH_LONG).show();
- }
- /**
- *自定义显示Toast时间
- *
- *@paramcontext
- *@parammessage
- *@paramduration
- */
- publicstaticvoidshow(Contextcontext,CharSequencemessage,intduration)
- {
- if(isShow)
- Toast.makeText(context,message,duration).show();
- }
- /**
- *自定义显示Toast时间
- *
- *@paramcontext
- *@parammessage
- *@paramduration
- */
- publicstaticvoidshow(Contextcontext,intmessage,intduration)
- {
- if(isShow)
- Toast.makeText(context,message,duration).show();
- }
- }
也是非常简单的一个封装,能省则省了~~
3、SharedPreferences封装类SPUtils- packagecom.zhy.utils;
- importjava.lang.reflect.InvocationTargetException;
- importjava.lang.reflect.Method;
- importjava.util.Map;
- importandroid.content.Context;
- importandroid.content.SharedPreferences;
- publicclassSPUtils
- {
- /**
- *保存在手机里面的文件名
- */
- publicstaticfinalStringFILE_NAME="share_data";
- /**
- *保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
- *
- *@paramcontext
- *@paramkey
- *@paramobject
- */
- publicstaticvoidput(Contextcontext,Stringkey,Objectobject)
- {
- SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
- Context.MODE_PRIVATE);
- SharedPreferences.Editoreditor=sp.edit();
- if(objectinstanceofString)
- {
- editor.putString(key,(String)object);
- }elseif(objectinstanceofInteger)
- {
- editor.putInt(key,(Integer)object);
- }elseif(objectinstanceofBoolean)
- {
- editor.putBoolean(key,(Boolean)object);
- }elseif(objectinstanceofFloat)
- {
- editor.putFloat(key,(Float)object);
- }elseif(objectinstanceofLong)
- {
- editor.putLong(key,(Long)object);
- }else
- {
- editor.putString(key,object.toString());
- }
- SharedPreferencesCompat.apply(editor);
- }
- /**
- *得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
- *
- *@paramcontext
- *@paramkey
- *@paramdefaultObject
- *@return
- */
- publicstaticObjectget(Contextcontext,Stringkey,ObjectdefaultObject)
- {
- SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
- Context.MODE_PRIVATE);
- if(defaultObjectinstanceofString)
- {
- returnsp.getString(key,(String)defaultObject);
- }elseif(defaultObjectinstanceofInteger)
- {
- returnsp.getInt(key,(Integer)defaultObject);
- }elseif(defaultObjectinstanceofBoolean)
- {
- returnsp.getBoolean(key,(Boolean)defaultObject);
- }elseif(defaultObjectinstanceofFloat)
- {
- returnsp.getFloat(key,(Float)defaultObject);
- }elseif(defaultObjectinstanceofLong)
- {
- returnsp.getLong(key,(Long)defaultObject);
- }
- returnnull;
- }
- /**
- *移除某个key值已经对应的值
- *@paramcontext
- *@paramkey
- */
- publicstaticvoidremove(Contextcontext,Stringkey)
- {
- SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
- Context.MODE_PRIVATE);
- SharedPreferences.Editoreditor=sp.edit();
- editor.remove(key);
- SharedPreferencesCompat.apply(editor);
- }
- /**
- *清除所有数据
- *@paramcontext
- */
- publicstaticvoidclear(Contextcontext)
- {
- SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
- Context.MODE_PRIVATE);
- SharedPreferences.Editoreditor=sp.edit();
- editor.clear();
- SharedPreferencesCompat.apply(editor);
- }
- /**
- *查询某个key是否已经存在
- *@paramcontext
- *@paramkey
- *@return
- */
- publicstaticbooleancontains(Contextcontext,Stringkey)
- {
- SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
- Context.MODE_PRIVATE);
- returnsp.contains(key);
- }
- /**
- *返回所有的键值对
- *
- *@paramcontext
- *@return
- */
- publicstaticMap<String,?>getAll(Contextcontext)
- {
- SharedPreferencessp=context.getSharedPreferences(FILE_NAME,
- Context.MODE_PRIVATE);
- returnsp.getAll();
- }
- /**
- *创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
- *
- *@authorzhy
- *
- */
- privatestaticclassSharedPreferencesCompat
- {
- privatestaticfinalMethodsApplyMethod=findApplyMethod();
- /**
- *反射查找apply的方法
- *
- *@return
- */
- @SuppressWarnings({"unchecked","rawtypes"})
- privatestaticMethodfindApplyMethod()
- {
- try
- {
- Classclz=SharedPreferences.Editor.class;
- returnclz.getMethod("apply");
- }catch(NoSuchMethodExceptione)
- {
- }
- returnnull;
- }
- /**
- *如果找到则使用apply执行,否则使用commit
- *
- *@parameditor
- */
- publicstaticvoidapply(SharedPreferences.Editoreditor)
- {
- try
- {
- if(sApplyMethod!=null)
- {
- sApplyMethod.invoke(editor);
- return;
- }
- }catch(IllegalArgumentExceptione)
- {
- }catch(IllegalAccessExceptione)
- {
- }catch(InvocationTargetExceptione)
- {
- }
- editor.commit();
- }
- }
- }
对SharedPreference的使用做了建议的封装,对外公布出put,get,remove,clear等等方法;
注意一点,里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit
首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
所以我们使用apply进行替代,apply异步的进行写入;
但是apply相当于commit来说是new API呢,为了更好的兼容,我们做了适配;
SharedPreferencesCompat也可以给大家创建兼容类提供了一定的参考~~
4、单位转换类DensityUtils- packagecom.zhy.utils;
- importandroid.content.Context;
- importandroid.util.TypedValue;
- /**
- *常用单位转换的辅助类
- *
- *
- *
- */
- publicclassDensityUtils
- {
- privateDensityUtils()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- /**
- *dp转px
- *
- *@paramcontext
- *@paramval
- *@return
- */
- publicstaticintdp2px(Contextcontext,floatdpVal)
- {
- return(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
- dpVal,context.getResources().getDisplayMetrics());
- }
- /**
- *sp转px
- *
- *@paramcontext
- *@paramval
- *@return
- */
- publicstaticintsp2px(Contextcontext,floatspVal)
- {
- return(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
- spVal,context.getResources().getDisplayMetrics());
- }
- /**
- *px转dp
- *
- *@paramcontext
- *@parampxVal
- *@return
- */
- publicstaticfloatpx2dp(Contextcontext,floatpxVal)
- {
- finalfloatscale=context.getResources().getDisplayMetrics().density;
- return(pxVal/scale);
- }
- /**
- *px转sp
- *
- *@paramfontScale
- *@parampxVal
- *@return
- */
- publicstaticfloatpx2sp(Contextcontext,floatpxVal)
- {
- return(pxVal/context.getResources().getDisplayMetrics().scaledDensity);
- }
- }
- packagecom.zhy.utils;
- importjava.io.File;
- importandroid.os.Environment;
- importandroid.os.StatFs;
- /**
- *SD卡相关的辅助类
- *
- *
- *
- */
- publicclassSDCardUtils
- {
- privateSDCardUtils()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- /**
- *判断SDCard是否可用
- *
- *@return
- */
- publicstaticbooleanisSDCardEnable()
- {
- returnEnvironment.getExternalStorageState().equals(
- Environment.MEDIA_MOUNTED);
- }
- /**
- *获取SD卡路径
- *
- *@return
- */
- publicstaticStringgetSDCardPath()
- {
- returnEnvironment.getExternalStorageDirectory().getAbsolutePath()
- +File.separator;
- }
- /**
- *获取SD卡的剩余容量单位byte
- *
- *@return
- */
- publicstaticlonggetSDCardAllSize()
- {
- if(isSDCardEnable())
- {
- StatFsstat=newStatFs(getSDCardPath());
- //获取空闲的数据块的数量
- longavailableBlocks=(long)stat.getAvailableBlocks()-4;
- //获取单个数据块的大小(byte)
- longfreeBlocks=stat.getAvailableBlocks();
- returnfreeBlocks*availableBlocks;
- }
- return0;
- }
- /**
- *获取指定路径所在空间的剩余可用容量字节数,单位byte
- *
- *@paramfilePath
- *@return容量字节SDCard可用空间,内部存储可用空间
- */
- publicstaticlonggetFreeBytes(StringfilePath)
- {
- //如果是sd卡的下的路径,则获取sd卡可用容量
- if(filePath.startsWith(getSDCardPath()))
- {
- filePath=getSDCardPath();
- }else
- {//如果是内部存储的路径,则获取内存存储的可用容量
- filePath=Environment.getDataDirectory().getAbsolutePath();
- }
- StatFsstat=newStatFs(filePath);
- longavailableBlocks=(long)stat.getAvailableBlocks()-4;
- returnstat.getBlockSize()*availableBlocks;
- }
- /**
- *获取系统存储路径
- *
- *@return
- */
- publicstaticStringgetRootDirectoryPath()
- {
- returnEnvironment.getRootDirectory().getAbsolutePath();
- }
- }
- packagecom.zhy.utils;
- importandroid.app.Activity;
- importandroid.content.Context;
- importandroid.graphics.Bitmap;
- importandroid.graphics.Rect;
- importandroid.util.DisplayMetrics;
- importandroid.view.View;
- importandroid.view.WindowManager;
- /**
- *获得屏幕相关的辅助类
- *
- *
- *
- */
- publicclassScreenUtils
- {
- privateScreenUtils()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- /**
- *获得屏幕高度
- *
- *@paramcontext
- *@return
- */
- publicstaticintgetScreenWidth(Contextcontext)
- {
- WindowManagerwm=(WindowManager)context
- .getSystemService(Context.WINDOW_SERVICE);
- DisplayMetricsoutMetrics=newDisplayMetrics();
- wm.getDefaultDisplay().getMetrics(outMetrics);
- returnoutMetrics.widthPixels;
- }
- /**
- *获得屏幕宽度
- *
- *@paramcontext
- *@return
- */
- publicstaticintgetScreenHeight(Contextcontext)
- {
- WindowManagerwm=(WindowManager)context
- .getSystemService(Context.WINDOW_SERVICE);
- DisplayMetricsoutMetrics=newDisplayMetrics();
- wm.getDefaultDisplay().getMetrics(outMetrics);
- returnoutMetrics.heightPixels;
- }
- /**
- *获得状态栏的高度
- *
- *@paramcontext
- *@return
- */
- publicstaticintgetStatusHeight(Contextcontext)
- {
- intstatusHeight=-1;
- try
- {
- Class<?>clazz=Class.forName("com.android.internal.R$dimen");
- Objectobject=clazz.newInstance();
- intheight=Integer.parseInt(clazz.getField("status_bar_height")
- .get(object).toString());
- statusHeight=context.getResources().getDimensionPixelSize(height);
- }catch(Exceptione)
- {
- e.printStackTrace();
- }
- returnstatusHeight;
- }
- /**
- *获取当前屏幕截图,包含状态栏
- *
- *@paramactivity
- *@return
- */
- publicstaticBitmapsnapShotWithStatusBar(Activityactivity)
- {
- Viewview=activity.getWindow().getDecorView();
- view.setDrawingCacheEnabled(true);
- view.buildDrawingCache();
- Bitmapbmp=view.getDrawingCache();
- intwidth=getScreenWidth(activity);
- intheight=getScreenHeight(activity);
- Bitmapbp=null;
- bp=Bitmap.createBitmap(bmp,0,0,width,height);
- view.destroyDrawingCache();
- returnbp;
- }
- /**
- *获取当前屏幕截图,不包含状态栏
- *
- *@paramactivity
- *@return
- */
- publicstaticBitmapsnapShotWithoutStatusBar(Activityactivity)
- {
- Viewview=activity.getWindow().getDecorView();
- view.setDrawingCacheEnabled(true);
- view.buildDrawingCache();
- Bitmapbmp=view.getDrawingCache();
- Rectframe=newRect();
- activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
- intstatusBarHeight=frame.top;
- intwidth=getScreenWidth(activity);
- intheight=getScreenHeight(activity);
- Bitmapbp=null;
- bp=Bitmap.createBitmap(bmp,0,statusBarHeight,width,height
- -statusBarHeight);
- view.destroyDrawingCache();
- returnbp;
- }
- }
- packagecom.zhy.utils;
- importandroid.content.Context;
- importandroid.content.pm.PackageInfo;
- importandroid.content.pm.PackageManager;
- importandroid.content.pm.PackageManager.NameNotFoundException;
- /**
- *跟App相关的辅助类
- *
- *
- *
- */
- publicclassAppUtils
- {
- privateAppUtils()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- /**
- *获取应用程序名称
- */
- publicstaticStringgetAppName(Contextcontext)
- {
- try
- {
- PackageManagerpackageManager=context.getPackageManager();
- PackageInfopackageInfo=packageManager.getPackageInfo(
- context.getPackageName(),0);
- intlabelRes=packageInfo.applicationInfo.labelRes;
- returncontext.getResources().getString(labelRes);
- }catch(NameNotFoundExceptione)
- {
- e.printStackTrace();
- }
- returnnull;
- }
- /**
- *[获取应用程序版本名称信息]
- *
- *@paramcontext
- *@return当前应用的版本名称
- */
- publicstaticStringgetVersionName(Contextcontext)
- {
- try
- {
- PackageManagerpackageManager=context.getPackageManager();
- PackageInfopackageInfo=packageManager.getPackageInfo(
- context.getPackageName(),0);
- returnpackageInfo.versionName;
- }catch(NameNotFoundExceptione)
- {
- e.printStackTrace();
- }
- returnnull;
- }
- }
- packagecom.zhy.utils;
- importandroid.content.Context;
- importandroid.view.inputmethod.InputMethodManager;
- importandroid.widget.EditText;
- /**
- *打开或关闭软键盘
- *
- *@authorzhy
- *
- */
- publicclassKeyBoardUtils
- {
- /**
- *打卡软键盘
- *
- *@parammEditText
- *输入框
- *@parammContext
- *上下文
- */
- publicstaticvoidopenKeybord(EditTextmEditText,ContextmContext)
- {
- InputMethodManagerimm=(InputMethodManager)mContext
- .getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.showSoftInput(mEditText,InputMethodManager.RESULT_SHOWN);
- imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
- InputMethodManager.HIDE_IMPLICIT_ONLY);
- }
- /**
- *关闭软键盘
- *
- *@parammEditText
- *输入框
- *@parammContext
- *上下文
- */
- publicstaticvoidcloseKeybord(EditTextmEditText,ContextmContext)
- {
- InputMethodManagerimm=(InputMethodManager)mContext
- .getSystemService(Context.INPUT_METHOD_SERVICE);
- imm.hideSoftInputFromWindow(mEditText.getWindowToken(),0);
- }
- }
- packagecom.zhy.utils;
- importandroid.app.Activity;
- importandroid.content.ComponentName;
- importandroid.content.Context;
- importandroid.content.Intent;
- importandroid.net.ConnectivityManager;
- importandroid.net.NetworkInfo;
- /**
- *跟网络相关的工具类
- *
- *
- *
- */
- publicclassNetUtils
- {
- privateNetUtils()
- {
- /*cannotbeinstantiated*/
- thrownewUnsupportedOperationException("cannotbeinstantiated");
- }
- /**
- *判断网络是否连接
- *
- *@paramcontext
- *@return
- */
- publicstaticbooleanisConnected(Contextcontext)
- {
- ConnectivityManagerconnectivity=(ConnectivityManager)context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if(null!=connectivity)
- {
- NetworkInfoinfo=connectivity.getActiveNetworkInfo();
- if(null!=info&&info.isConnected())
- {
- if(info.getState()==NetworkInfo.State.CONNECTED)
- {
- returntrue;
- }
- }
- }
- returnfalse;
- }
- /**
- *判断是否是wifi连接
- */
- publicstaticbooleanisWifi(Contextcontext)
- {
- ConnectivityManagercm=(ConnectivityManager)context
- .getSystemService(Context.CONNECTIVITY_SERVICE);
- if(cm==null)
- returnfalse;
- returncm.getActiveNetworkInfo().getType()==ConnectivityManager.TYPE_WIFI;
- }
- /**
- *打开网络设置界面
- */
- publicstaticvoidopenSetting(Activityactivity)
- {
- Intentintent=newIntent("/");
- ComponentNamecm=newComponentName("com.android.settings",
- "com.android.settings.WirelessSettings");
- intent.setComponent(cm);
- intent.setAction("android.intent.action.VIEW");
- activity.startActivityForResult(intent,0);
- }
- }
- packagecom.zhy.utils;
- importjava.io.BufferedReader;
- importjava.io.ByteArrayOutputStream;
- importjava.io.IOException;
- importjava.io.InputStream;
- importjava.io.InputStreamReader;
- importjava.io.PrintWriter;
- importjava.net.HttpURLConnection;
- importjava.net.URL;
- /**
- *Http请求的工具类
- *
- *@authorzhy
- *
- */
- publicclassHttpUtils
- {
- privatestaticfinalintTIMEOUT_IN_MILLIONS=5000;
- publicinterfaceCallBack
- {
- voidonRequestComplete(Stringresult);
- }
- /**
- *异步的Get请求
- *
- *@paramurlStr
- *@paramcallBack
- */
- publicstaticvoiddoGetAsyn(finalStringurlStr,finalCallBackcallBack)
- {
- newThread()
- {
- publicvoidrun()
- {
- try
- {
- Stringresult=doGet(urlStr);
- if(callBack!=null)
- {
- callBack.onRequestComplete(result);
- }
- }catch(Exceptione)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- /**
- *异步的Post请求
- *@paramurlStr
- *@paramparams
- *@paramcallBack
- *@throwsException
- */
- publicstaticvoiddoPostAsyn(finalStringurlStr,finalStringparams,
- finalCallBackcallBack)throwsException
- {
- newThread()
- {
- publicvoidrun()
- {
- try
- {
- Stringresult=doPost(urlStr,params);
- if(callBack!=null)
- {
- callBack.onRequestComplete(result);
- }
- }catch(Exceptione)
- {
- e.printStackTrace();
- }
- };
- }.start();
- }
- /**
- *Get请求,获得返回数据
- *
- *@paramurlStr
- *@return
- *@throwsException
- */
- publicstaticStringdoGet(StringurlStr)
- {
- URLurl=null;
- HttpURLConnectionconn=null;
- InputStreamis=null;
- ByteArrayOutputStreambaos=null;
- try
- {
- url=newURL(urlStr);
- conn=(HttpURLConnection)url.openConnection();
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- conn.setRequestMethod("GET");
- conn.setRequestProperty("accept","*/*");
- conn.setRequestProperty("connection","Keep-Alive");
- if(conn.getResponseCode()==200)
- {
- is=conn.getInputStream();
- baos=newByteArrayOutputStream();
- intlen=-1;
- byte[]buf=newbyte[128];
- while((len=is.read(buf))!=-1)
- {
- baos.write(buf,0,len);
- }
- baos.flush();
- returnbaos.toString();
- }else
- {
- thrownewRuntimeException("responseCodeisnot200...");
- }
- }catch(Exceptione)
- {
- e.printStackTrace();
- }finally
- {
- try
- {
- if(is!=null)
- is.close();
- }catch(IOExceptione)
- {
- }
- try
- {
- if(baos!=null)
- baos.close();
- }catch(IOExceptione)
- {
- }
- conn.disconnect();
- }
- returnnull;
- }
- /**
- *向指定URL发送POST方法的请求
- *
- *@paramurl
- *发送请求的URL
- *@paramparam
- *请求参数,请求参数应该是name1=value1&name2=value2的形式。
- *@return所代表远程资源的响应结果
- *@throwsException
- */
- publicstaticStringdoPost(Stringurl,Stringparam)
- {
- PrintWriterout=null;
- BufferedReaderin=null;
- Stringresult="";
- try
- {
- URLrealUrl=newURL(url);
- //打开和URL之间的连接
- HttpURLConnectionconn=(HttpURLConnection)realUrl
- .openConnection();
- //设置通用的请求属性
- conn.setRequestProperty("accept","*/*");
- conn.setRequestProperty("connection","Keep-Alive");
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.setRequestProperty("charset","utf-8");
- conn.setUseCaches(false);
- //发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
- conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
- if(param!=null&&!param.trim().equals(""))
- {
- //获取URLConnection对象对应的输出流
- out=newPrintWriter(conn.getOutputStream());
- //发送请求参数
- out.print(param);
- //flush输出流的缓冲
- out.flush();
- }
- //定义BufferedReader输入流来读取URL的响应
- in=newBufferedReader(
- newInputStreamReader(conn.getInputStream()));
- Stringline;
- while((line=in.readLine())!=null)
- {
- result+=line;
- }
- }catch(Exceptione)
- {
- e.printStackTrace();
- }
- //使用finally块来关闭输出流、输入流
- finally
- {
- try
- {
- if(out!=null)
- {
- out.close();
- }
- if(in!=null)
- {
- in.close();
- }
- }catch(IOExceptionex)
- {
- ex.printStackTrace();
- }
- }
- returnresult;
- }
- }
如果大家在使用过程中出现什么错误,或者有更好的建议,欢迎大家留言提出~~可以不断的改进这些类~