异步网络请求的一些操作

mTask = BusinessResolve.login(email, password, new BusinessCallback<LoginResBean>() {

			@Override
			public void onSuccess(LoginResBean data) {

				PreferenceUtil.putInt(Preferences.USER_ID, data.User.Id);
				PreferenceUtil.putString(Preferences.TOKEN, data.User.Token);
				PreferenceUtil.putString(User.REGISTER_TIME, TimeUtil.string2String4(data.User.RegisterTime));
				List<RepositoryResBean> devices = data.User.Repositories;
				if (devices.size() > 0) {
					PreferenceUtil.putInt(Preferences.REPOSITORY_ID, devices.get(0).Id);
					PreferenceUtil.putString(com.xinqiantu.healthband.ble.cons.Preferences.DEVICE_SERIAL, devices.get(0).Serial);
				}
				/** 默认个人信息 **/
				PreferenceUtil.putBoolean(User.GENDER, true);
				PreferenceUtil.putString(User.BIRTHDAY, "1990-01-01");
				PreferenceUtil.putInt(User.HEIGHT, 170);
				PreferenceUtil.putInt(User.WEIGHT, 65);
				PreferenceUtil.putInt(User.STEP_SIZE, 70);
				PreferenceUtil.putString(User.CITY, "未选择");
				PreferenceUtil.putInt(User.STEP_GOAL, 10000);

				Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				startActivity(intent);

				closeProgressBar();
				setResult(RESULT_OK);
				finish();

			}

			@Override
			public void onError(BusinessException e) {
				AppMsg.makeText(LoginActivity.this, e.getMessage());
				closeProgressBar();
			}


 

public interface BusinessCallback<T> {

	/**
	 * code为100:数据成功返回
	 * 
	 * @param data
	 *            响应数据的封装对象
	 */
	public void onSuccess(T data);

	/**
	 * code不为100:请求失败,包含网络问题,服务端问题
	 * 
	 * @param e
	 */
	public void onError(BusinessException e);

}


 

public static BusinessTask login(String email, String password, BusinessCallback<LoginResBean> callback) {
		LoginReqBean requestBean = new LoginReqBean();
		requestBean.Username = email;
		requestBean.Password = password;

		BusinessRequest params = new BusinessRequest();
		params.functionName = Function.LOGIN;
		params.object = requestBean;
		params.responseClass = LoginResBean.class;

		BusinessTask task = new BusinessTask(callback);
		task.execute(params);
		return task;
	}


 

public class LoginResBean {

	public UserResBean User;

	@Override
	public String toString() {
		return "LoginResBean [User=" + User + "]";
	}

}


 

class BusinessRequest {
 
	String functionName;   //URL名字

	Class<?> responseClass;  //对象泛型

	Object object;  //对象

}


 

public class BusinessTask extends AsyncTask<BusinessRequest, Void, BusinessResult> {

	@SuppressWarnings("rawtypes")
	private BusinessCallback mCallback;

	public BusinessTask(BusinessCallback<?> callback) {
		this.mCallback = callback;
	}

	@Override
	protected BusinessResult doInBackground(BusinessRequest... params) {
		BusinessRequest request = params[0];  
		BusinessResult result = new BusinessResult();

		/** 进行HPROSE请求 */
		String pramData = null;
		try {
			if (request.object instanceof UploadFileRequestBean) { //上传图片到服务端操作
				pramData = Http.doUploadFile(request.functionName, ((UploadFileRequestBean) (request.object)).generateMap());
			} else {
				//执行登录异步网络请求操作
				pramData = Http.doPost(request.functionName, request.object);
			}
		} catch (BusinessException e) {
			result.exception = e;
			result.success = false;
			return result;
		}

		/** 将成功情况下返回参数data对应的值,解析为对象 */
		Object returnObject = null;
		try {
			if (request.responseClass != null && !TextUtils.isEmpty(pramData)) {
				returnObject = JsonUtil.objectFromJson(pramData, request.responseClass); //将字符串解析成为对象
			}
			if (BuildConfig.DEBUG) {
				L.i("Http 请求接口 >>" + request.functionName + "<< 解析对象: " + returnObject);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.exception = new BusinessException(BusinessException.CODE_PARSE_JSON_ERROR);
			result.success = false;
			return result;
		}
		/** 默认成功 */
		result.returnObject = returnObject;
		result.success = true;
		return result;
	}

	@Override
	protected void onPostExecute(BusinessResult result) {
		if (mCallback != null && !isCancelled()) {
			if (result.success) {
				mCallback.onSuccess(result.returnObject); //成功返回对象
			} else {
				mCallback.onError(result.exception);
				if (result.exception.getMessage().equals(BusinessException.TOKEN_INVALID)) {
					TokenInvalidUtil.showDialog();
				}
			}
		}
	}

}


 

class BusinessResult {

	Object returnObject;  //对象

	boolean success; //返回的状态码

	BusinessException exception; //提示在连接异步网络的时候报哪一种异常
}


 

public class HttpUrlConnectionUtil {

	public String doPost(String functionName, String requestBody) throws BusinessException {
		HttpURLConnection con = null;
		StringBuffer buffer = null;
		try {
			System.out.println("Http - url " + HttpConstants.uri + functionName);
			URL u = new URL(HttpConstants.uri + functionName);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setConnectTimeout(HttpConstants.TIMEOUT);
			con.setReadTimeout(HttpConstants.TIMEOUT);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type", "application/json");
			String agent = "Steward " + HttpConstants.VERSION + " (android " + android.os.Build.VERSION.RELEASE + ";" + android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL + ")";
			con.setRequestProperty("User-Agent", agent);
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), HttpConstants.ENCODEING);
			osw.write(requestBody);
			osw.flush();
			osw.close();
			System.out.println("Http - responseCode " + con.getResponseCode());

			/** 读取返回内容 */
			buffer = new StringBuffer();
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), HttpConstants.ENCODEING));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
				buffer.append("\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(BusinessException.CODE_UNREACH_SERVER);
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		return buffer.toString();
	}

	/**
	 * 上传头像
	 * 
	 * @param filePath
	 * @param data
	 * @return
	 * @throws BusinessException
	 */
	public String doUploadFile(String functionName, String filePath, HashMap<String, String> mapData) throws BusinessException {
		HttpURLConnection con = null;
		StringBuffer bufferReceive = null;
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		try {
			URL url = new URL(HttpConstants.uri + functionName);
			con = (HttpURLConnection) url.openConnection();

			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false);

			con.setRequestMethod("POST");

			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", HTTP.UTF_8);
			con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

			DataOutputStream ds = new DataOutputStream(con.getOutputStream());

			ds.writeBytes(twoHyphens + boundary + end);
			ds.writeBytes("Content-Disposition: form-data; " + "name=Avatar; filename=new.png" + end);
			ds.writeBytes("Content-Type: image/png" + end);
			ds.writeBytes(end);
			FileInputStream fStream = new FileInputStream(filePath);
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];
			int length = -1;
			while ((length = fStream.read(buffer)) != -1) {
				ds.write(buffer, 0, length);
			}
			fStream.close();
			ds.writeBytes(end);

			for (String key : mapData.keySet()) {
				ds.writeBytes(twoHyphens + boundary + end);
				ds.writeBytes("Content-Disposition: form-data; " + "name=" + key + end);
				ds.writeBytes(end);
				ds.writeBytes(mapData.get(key) + end);
			}

			ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
			ds.flush();
			ds.close();
			System.out.println("Http - responseCode " + con.getResponseCode());

			/** 读取返回内容 */
			bufferReceive = new StringBuffer();
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), HTTP.UTF_8));
			String temp;
			while ((temp = br.readLine()) != null) {
				bufferReceive.append(temp);
				bufferReceive.append("\n");
			}
			System.out.println(bufferReceive.toString());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(BusinessException.CODE_UNREACH_SERVER);
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		return bufferReceive.toString();
	}


你可能感兴趣的:(异步网络请求的一些操作)