비동기식 네트워크 요청 작업

8858 단어
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("
"); } } 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
"; 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("
"); } 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(); }

좋은 웹페이지 즐겨찾기