import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import com.lidroid.xutils.BitmapUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
/**
* Created by blueZhang
* at 2015/12/4 0004.
* Email bluezhang521@163.com
*/
/**
* use to connect with internet ,get or push data .
*/
public final class EHttpUtil {
private static final int CONNECT_TIMEOUT = 5000; //timeout
private static final int READ_TIMEOUT = 5000; // read data timeout
public static final String USER_AGENT = "ting_4.1.7(" + Build.MODEL + "," + Build.VERSION.SDK_INT + ")";
public EHttpUtil() {
throw new IllegalStateException("the bitmapUtils Object is an static Object,you don't need to new! ");
}
public static BitmapUtils bitmapUtils;
////////////////////////////////////////////////////////////////////////////////////////////
/**
* the interface to use when response
*/
public interface CallBack {
/**
* method to receive success message<br/>
* if you want to get the success message,you need use this method responseInfo.result();获取返回值信息
*
* @param responseInfo response信息
*/
void onSuccess(ResponseInfo<String> responseInfo);
/**
* call when the request is failure,
*
* @param error wrong Object
* @param msg error message
*/
void onFailure(HttpException error, String msg);
}
//////////////////////////////////////////////////////////////////////////////////////////////
/**
* initialization BitmapUtil object
*
* @param context context
* @param filePath file path
* @param cacheSize cache size
* @return
*/
public static BitmapUtils newInstance(Context context, String filePath, int cacheSize) {
return getBitmapUtils(context, filePath, cacheSize);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @param context context
* @param filePath the file path we need to save
* @param cacheSize the size of cache to cache image
* @return bitmapUtils Object
*/
public static BitmapUtils getBitmapUtils(Context context, String filePath, int cacheSize) {
if (filePath == null || cacheSize == 0) {
bitmapUtils = new BitmapUtils(context);
} else {
bitmapUtils = new BitmapUtils(context, filePath, cacheSize);
}
bitmapUtils.configDefaultBitmapMaxSize(512, 256);
bitmapUtils.configDefaultConnectTimeout(CONNECT_TIMEOUT);
bitmapUtils.configDiskCacheEnabled(true);//设置可以缓存
// bitmapUtils.configThreadPoolSize(5);//默认线程池中就是五个线程
// bitmapUtils.configDefaultImageLoadAnimation() //添加图片加载的时候的动画
// bitmapUtils.configDefaultLoadFailedImage(R.mipmap.a)//设置加载图片失败显示的图片
// bitmapUtils.configDefaultLoadingImage(R.mipmap.) //设置记载图片占位图
return bitmapUtils;
}
////////////////////////////////////////////////////////////////////////////////////////
/**
* get data from internet ,use GET
*
* @param url the urk to get data
* @param callBack the callBack of response
*/
public static void getStringUseGET(String url, final CallBack callBack) {
RequestParams params = new RequestParams();
params.addHeader("Accept-Encoding", "gzip");
params.addHeader("User-Agent", USER_AGENT);
HttpUtils httpUtils;
httpUtils = new HttpUtils();
httpUtils.send(
HttpRequest.HttpMethod.GET,
url,
params,
new RequestCallBack<String>() {
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
callBack.onSuccess(responseInfo);
}
@Override
public void onFailure(HttpException error, String msg) {
callBack.onFailure(error, msg);
}
});
}
///////////////////////////////////////////////////////////////////////////////////////////
/**
* the method to download the file
*
* @param context the context
* @param dPath download path
* @param fileName download file name
*/
public static void downloadFile(final Context context, String dPath, String fileName) {
HttpUtils httpUtils = new HttpUtils();
String mPath = getFileDownloadPath(context);
if (mPath != null) {
HttpHandler handler = httpUtils.download(
dPath,//the path to download file
mPath + "/" + fileName,//the path to save file
true,//if the file is exist but not complete ,continue to download it
true,//if get file name from head ,rename the file with it
new RequestCallBack<File>() {
@Override
public void onStart() {
super.onStart();
T.showShort(context, "download is running in background");
}
@Override
public void onLoading(long total, long current, boolean isUploading) {
super.onLoading(total, current, isUploading);
//TODO I don't know should we need this ,so just put it here
}
@Override
public void onSuccess(ResponseInfo<File> responseInfo) {
L.d("the download is success :" + responseInfo.result.getAbsolutePath());
T.showShort(context, "download success !");
}
@Override
public void onFailure(HttpException error, String msg) {
L.d("the download is failure for this reasion :" + msg);
}
@Override
public void onCancelled() {
super.onCancelled();
}
});
}else {
throw new NullPointerException("the phone path is null,please check your phone!");
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
/**
* get the absolute path to save download file
*
* @param context the context
* @return file path
*/
public static String getFileDownloadPath(Context context) {
String ret ;
if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {//if the SDCard is mounted we store the file to sdcard
ret = Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
ret = context.getFilesDir().getAbsolutePath();
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////////////
/**
* use post to pull data
* @param strUrlPath path
* @param params params
* @param encode encode
* @return edited String
*/
public static String submitPostData(String strUrlPath,Map<String, String> params, String encode) {
byte[] data = getRequestData(params, encode).toString().getBytes();//get request params
try {
URL url = new URL(strUrlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000); //timeout
httpURLConnection.setDoInput(true); //open inputStream
httpURLConnection.setDoOutput(true); //open OutPuStream
httpURLConnection.setRequestMethod("POST"); //method
httpURLConnection.setUseCaches(false); //no cache
//set header
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//request body length
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
//get OutPutStream
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(data);
int response = httpURLConnection.getResponseCode(); //response code
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
return dealResponseResult(inptStream);
}
} catch (IOException e) {
//e.printStackTrace();
return "err: " + e.getMessage().toString();
}
return "-1";
}
/**
* encapsulation the params
* @param params parameter
* @param encode encoding
* @return buffer
*/
public static StringBuffer getRequestData(Map<String, String> params, String encode) {
StringBuffer stringBuffer = new StringBuffer(); //request body
try {
for(Map.Entry<String, String> entry : params.entrySet()) {
stringBuffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(), encode))
.append("&");
}
stringBuffer.deleteCharAt(stringBuffer.length() - 1);
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer;
}
/**
* response
* @param inputStream input stream
* @return handled message
*/
public static String dealResponseResult(InputStream inputStream) {
String resultData ; //save message
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len;
try {
while((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(byteArrayOutputStream.toByteArray());
return resultData;
}
}
离职了,网络请求工具类发出来,大家需要的拿走,Xutils的
最新推荐文章于 2025-06-27 15:51:03 发布
本文介绍了一个用于Android平台的网络请求库XUtils的使用方法,包括初始化BitmapUtils对象、通过GET方式获取网络数据、下载文件等功能,并提供了详细的代码实现。
716

被折叠的 条评论
为什么被折叠?



