android与后台交互

package net.shopnc.shop.http;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import android.util.Log;


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.pfk.love7.entity.BloodOxygenAdviceInfo;
import com.pfk.love7.entity.BloodOxygenInfo;
import com.pfk.love7.entity.BloodSugarAdviceInfo;
import com.pfk.love7.entity.BloodSugarItem;
import com.pfk.love7.entity.ECGAdviceInfo;
import com.pfk.love7.entity.ECGInfo;
import com.pfk.love7.entity.ErrClass;
import com.pfk.love7.entity.HealthReport;
import com.pfk.love7.entity.HealthReportContent;
import com.pfk.love7.entity.PlanInfo;
import com.pfk.love7.entity.ResultInfo;
import com.pfk.love7.entity.Status;
import com.pfk.love7.entity.TempAdviceInfo;
import com.pfk.love7.entity.TempInfo;
import com.pfk.love7.entity.UserInfo;


/**
 * @description 通过Http协议与服务端进行通信操作的工具类
 * 
 * @author 张晓迁
 *
 * @date 2015年9月25日 下午5:05:42
 */
public class HttpUtils {


private static final String TAG = "HttpUtils";


private static final String BASE_URL = "http://27.255.94.157:8395/";
// private static final String BASE_URL = "http://205.209.161.238:8395/";
// private static final String BASE_URL = "http://192.168.101.85:8395/";


public static final int SUCCESS = 0x1001;
public static final int ERROR = 0x1002;


// http请求
public static final String HTPP_SUCESS = "1"; // 成功
public static final String HTPP_FAILED = "0"; // 失败


/**
* 新用户注册

* @param mobNum
*            手机号
* @param password
*            密码
* @return
*/
public static ErrClass register(String mobNum, String password) {


String url = BASE_URL + "AiUsers/add/" + mobNum + "/" + password;
return getInfo(url, ErrClass.class);


}


/**
* 更改密码

* @param mobNum
*            手机号
* @param password
*            新密码
* @return
*/
public static ErrClass updatePassword(String mobNum, String password) {
String url = BASE_URL + "AiUsers/UpdUpwd";
JSONObject param = new JSONObject();
try {
param.put("mobNum", mobNum);
param.put("pwd", password);
String result = post(url, param.toString());
Log.d(TAG, "result = " + result);
return fromJson(result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}


/**
* 根据IMEI号获取蓝牙模块的MAC地址

* @param IMEI
*            手机IMEI号
* @return
*/
public static ErrClass getMac(String IMEI) {
String url = BASE_URL + "AiUsers/getMac/" + IMEI;
return getInfo(url, ErrClass.class);
}


/**
* 根据手机号查询个人信息

* @param mobNum
*            手机号
* @return
*/
public static UserInfo getUserInfo(String mobNum) {
String url = BASE_URL + "AiUsers/getOneUser/" + mobNum;
return getInfo(url, UserInfo.class);
}


/**
* 更新个人信息

* @param info
*            个人信息
* @return
*/
public static ErrClass updateUserInfo(UserInfo info) {
String url = BASE_URL + "AiUsers/UpdUserMess";
JSONObject param = new JSONObject();
try {
param.put("mobNum", info.getMobNum());
param.put("uName", info.getuName());
param.put("uSex", info.getuSex());
param.put("uHeight", info.getuHeight());
param.put("uWeight", info.getuWeight());
param.put("uBirthday", info.getuBirthday());
String result = post(url, param.toString());
Log.d(TAG, "result = " + result);
return fromJson(result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}


/**
* 查询最近七次测量的体温值

* @param mobNum
*            手机号
* @return
*/
public static List<TempInfo> getTempInfoList(String mobNum) {
String url = BASE_URL + "Business/BodyTemSevenList/" + mobNum;
return getTempList(url);
}


/**
* 查询时间段内测量的体温值

* @param mobNum
*            手机号
* @param startTime
*            开始时间
* @param stopTime
*            结束时间
* @return
*/
public static List<TempInfo> getTempInfoList(String mobNum, String startTime, String stopTime) {
String url = BASE_URL + "Business/BodyTemList/" + mobNum + "/" + startTime + "/" + stopTime;
return getTempList(url);
}


/**
* 查询测量的体温值

* @param url
* @return
*/
private static List<TempInfo> getTempList(String url) {
return getInfoList(url, TempInfo.class);
}


/**
* 查询体温状态和对应次数

* @param mobNum
*            手机号
* @return
*/
public static List<Status> getTempStatusNumList(String mobNum) {
String url = BASE_URL + "Business/BodyTemTypeList/" + mobNum;
return getStatusNumList(url);
}


/**
* 根据温度测量值返回相应的建议

* @param num
*            温度值
*/
public static TempAdviceInfo getTempAdviceByNum(String num) {
String url = BASE_URL + "Business/BodyTemperatureSuggest/" + num;
return getInfo(url, TempAdviceInfo.class);
}


/**
* 查询体温和建议信息

* @param id
* @return
*/
public static TempAdviceInfo getOneTemp(String id) {
String url = BASE_URL + "Business/BodyTemOne/" + id;
return getInfo(url, TempAdviceInfo.class);
}


/**
* 查询自我规划的列表

* @param mobNum
*            手机号
* @return
*/
public static List<PlanInfo> getPlanInfoList(String mobNum) {
String url = BASE_URL + "News/MyPlans/" + mobNum;
return getInfoList(url, PlanInfo.class);
}


/**
* 添加个人规划

* @param info
*            个人规划信息
* @return
*/
public static ErrClass addPlan(PlanInfo info) {
String url = BASE_URL + "News/addPlan";
JSONObject param = new JSONObject();
try {
param.put("spTitle", info.getSpTitle());
param.put("content", info.getSpContent());
param.put("startTime", info.getSpStartTime());
param.put("userNo", info.getSpUserNo());
String result = post(url, param.toString());
Log.d(TAG, "result = " + result);
return fromJson(result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}


/**
* 解析Json字符串

* @param jsonString
* @return
*/
private static ErrClass fromJson(String jsonString) {
try {
if (jsonString == null) {
return null;
}
jsonString = jsonString.replace("\\", "");
jsonString = jsonString.substring(1, jsonString.length() - 1);
Gson gson = new Gson();
return gson.fromJson(jsonString, ErrClass.class);
} catch (JsonSyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}


/**
* 修改个人规划

* @param info
*            个人规划信息
* @return
*/
public static ErrClass updatePlan(PlanInfo info) {
String url = BASE_URL + "News/UpdPlan";
JSONObject param = new JSONObject();
try {
param.put("spTitle", info.getSpTitle());
param.put("content", info.getSpContent());
param.put("startTime", info.getSpStartTime());
param.put("spId", info.getSpId());
String result = post(url, param.toString());
Log.d(TAG, "result = " + result);
return fromJson(result);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}


/**
* 根据计划主键查询单条计划信息

* @param id
* @return
*/
public static PlanInfo getPlanInfo(String id) {
String url = BASE_URL + "News/OnePlan/" + id;
return getInfo(url, PlanInfo.class);
}


/**
* 查询最近七次测量的血糖值

* @param mobNum
*            手机号
* @return
*/
public static List<BloodSugarItem> getBloodSugarInfoList(String mobNum) {
String url = BASE_URL + "Business/BloodGluSevenList/" + mobNum;
return getBloodSugarList(url);
}


/**
* 查询时间段内测量的血糖值

* @param mobNum
*            手机号
* @param startTime
*            开始时间
* @param stopTime
*            结束时间
* @return
*/
public static List<BloodSugarItem> getBloodSugarInfoList(String mobNum, String startTime, String stopTime) {
String url = BASE_URL + "Business/BloodGluList/" + mobNum + "/" + startTime + "/" + stopTime;
return getBloodSugarList(url);
}


/**
* 查询测量的血糖值

* @param url
* @return
*/
private static List<BloodSugarItem> getBloodSugarList(String url) {
return getInfoList(url, BloodSugarItem.class);
}


/**
* 根据血糖测量值返回相应的建议

* @param num
*            温度值
*/
public static BloodSugarAdviceInfo getBloodSugarAdviceByNum(String num, String time) {
String url = BASE_URL + "Business/BloodGlucoseSuggest/" + num + "/" + time;
return getInfo(url, BloodSugarAdviceInfo.class);
}


/**
* 查询血糖和建议信息

* @param id
* @return
*/
public static BloodSugarAdviceInfo getOneBloodSugar(String id) {
String url = BASE_URL + "Business/BloodGluOne/" + id;
return getInfo(url, BloodSugarAdviceInfo.class);
}


/**
* 查询血糖状态和对应次数

* @param mobNum
*            手机号
* @return
*/
public static List<Status> getBloodSugarStatusNumList(String mobNum) {
String url = BASE_URL + "Business/BloodGluTypeList/" + mobNum;
return getStatusNumList(url);
}


/**
* 查询最近七次测量的血氧值

* @param mobNum
*            手机号
* @return
*/
public static List<BloodOxygenInfo> getBloodOxygenInfoList(String mobNum) {
String url = BASE_URL + "Business/OxygenSevenList/" + mobNum;
return getBloodOxygenList(url);
}


/**
* 查询时间段内测量的血氧值

* @param mobNum
*            手机号
* @param startTime
*            开始时间
* @param stopTime
*            结束时间
* @return
*/
public static List<BloodOxygenInfo> getBloodOxygenInfoList(String mobNum, String startTime, String stopTime) {
String url = BASE_URL + "Business/OxygenList/" + mobNum + "/" + startTime + "/" + stopTime;
return getBloodOxygenList(url);
}


/**
* 查询测量的血氧值

* @param url
* @return
*/
private static List<BloodOxygenInfo> getBloodOxygenList(String url) {
return getInfoList(url, BloodOxygenInfo.class);
}


/**
* 查询血氧和建议信息

* @param id
* @return
*/
public static BloodOxygenAdviceInfo getOneBloodOxygen(String id) {
String url = BASE_URL + "Business/OxygenOne/" + id;
return getInfo(url, BloodOxygenAdviceInfo.class);
}


/**
* 查询血氧状态和对应次数

* @param mobNum
*            手机号
* @return
*/
public static List<Status> getBloodOxygenStatusNumList(String mobNum) {
String url = BASE_URL + "Business/OxygenTypeList/" + mobNum;
return getStatusNumList(url);
}


/**
* 根据手机号和日期查询心电列表

* @param mobNum
*            手机号
* @param time
*            日期
* @return
*/
public static List<ECGInfo> getECGList(String mobNum, String time) {
String url = BASE_URL + "Business/EcgList/" + mobNum + "/" + time;
return getInfoList(url, ECGInfo.class);
}


/**
* 根据心电主键查询一条心电记录

* @param id
* @return
*/
public static ECGAdviceInfo getOneECG(String id) {
String url = BASE_URL + "Business/ECGOne/" + id;
return getInfo(url, ECGAdviceInfo.class);
// getFile(url);
// get1(url);
}


/**
* 查询状态和对应次数

* @param url
* @return
*/
private static List<Status> getStatusNumList(String url) {
return getInfoList(url, Status.class);
}


/**
* 获取健康报告列表

* @param mobNum
*            手机号
* @return
*/
public static List<HealthReport> getHealthReportList(String mobNum) {
String url = BASE_URL + "Business/HealthReportList/" + mobNum;
return getInfoList(url, HealthReport.class);
}


/**
* 获取健康报告详细内容

* @param id
* @return
*/
public static List<HealthReportContent> getDetailHealthReport(String id) {
String url = BASE_URL + "Business/getDetailHealthReport/" + id;
return getInfoList(url, HealthReportContent.class);
}


/**
* 根据(手机号)用户名查询最近一次的检测结果

* @param mobNum
*            手机号
* @return
*/
public static List<ResultInfo> getResultInfo(String mobNum) {
String url = BASE_URL + "Business/LastestMeasureResult/" + mobNum;
return getInfoList(url, ResultInfo.class);
}


/**
* 获取手机验证码

* @param mobNum
*            手机号
* @return
*/
public static ErrClass getIdentifyingCode(String mobNum) {
String url = BASE_URL + "AiUsers/getIdentifyingCode/" + mobNum;
return getInfo(url, ErrClass.class);
}


/**
* 查询数据

* @param url
*            url
* @param cls
*            实体类
* @return
*/
private static <T> T getInfo(String url, Class<?> cls) {
T t = null;
try {
String result = get(url);
if (null == result || ("").equals(result)) {
return t;
}
Log.d(TAG, "result = " + result);
result = result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1);
t = parseInfo(result, cls);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return t;
}
return t;
}


/**
* 查询列表数据

* @param url
*            url
* @param cls
*            实体类
* @return
*/
private static <T> List<T> getInfoList(String url, Class<?> cls) {
List<T> tList = new ArrayList<T>();
try {
String result = get(url);
if (null == result || ("").equals(result)) {
return tList;
}
Log.d(TAG, "result = " + result);
result = result.substring(result.indexOf("{"), result.lastIndexOf("}") + 1);
tList = parseInfoList(result, cls);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return tList;
}
return tList;
}


/**
* 解析返回的数据

* @param <T>

* @param json
*            待解析的json数据
* @param cls
*            数据对象
* @return 查询结果
*/


private static <T> T parseInfo(String json, Class<?> cls) {
Gson gson = new Gson();
return (T) gson.fromJson(json, cls);
}


/**
* 解析返回的数据列表

* @param <T>

* @param json
*            待解析的json数据
* @param cls
*            数据对象
* @return 查询结果列表
*/
private static <T> List<T> parseInfoList(String json, Class<?> cls) {
List<T> results = new ArrayList<T>();
Gson gson = new Gson();
try {
JSONArray jsonArray = new JSONObject(json).optJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
results.add((T) gson.fromJson(jsonArray.getJSONObject(i).toString(), cls));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return results;
}


private static File getFile(String url) {
String filePath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + "/love7/file/";


if (!new File(filePath).exists()) {
new File(filePath).mkdirs();
}
String fileName = url.substring(url.lastIndexOf("/") + 1);
File f = new File(filePath + fileName);


// 先从文件缓存中查找是否有
if (f != null && f.exists()) {
return f;
}


// 最后从指定的url中下载文件
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
return f;
} catch (Exception ex) {
Log.e("", "getFile catch Exception...\nmessage = " + ex.getMessage());
return null;
}
}


private static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
os.write(bytes, 0, count);
}
} catch (Exception ex) {
Log.e("", "CopyStream catch Exception...");
}
}


/**
* post的http请求

* @param url
* @param json
* @return
*/
private static String post(String url, String json) {
HttpPost request = null;
try {
// 获得HttpPost对象
request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json");
} catch (IllegalArgumentException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if (request == null) {
return null;
}
if (json != null) {
try {
StringEntity entity = new StringEntity(json, "UTF-8");
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO: handle exception
e.printStackTrace();
}
}


String result = null;
try {
HttpResponse response = new DefaultHttpClient().execute(request);
int resultCode = response.getStatusLine().getStatusCode();
Log.d(TAG, "resultCode = " + resultCode);
if (resultCode == 200) {
result = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}


/**
* get的http请求

* @param url
* @return
*/
private static String get(String url) {
HttpGet request = null;
try {
// 获得HttpGet对象
request = new HttpGet(url);
} catch (IllegalArgumentException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if (request == null) {
return null;
}


String result = null;
try {
HttpResponse response = new DefaultHttpClient().execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity());
}
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
return result;
}


/**
* get的http请求

* @param url
* @return
*/
private static String get1(String url) {
HttpGet request = null;
try {
// 获得HttpGet对象
request = new HttpGet(url);
} catch (IllegalArgumentException e) {
// TODO: handle exception
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
if (request == null) {
return null;
}


String result = null;
try {
HttpResponse response = new DefaultHttpClient().execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
final InputStream is = response.getEntity().getContent();
BufferedReader buReader = new BufferedReader(new InputStreamReader(is));
for (String s = buReader.readLine(); s != null; s = buReader.readLine()) {
Log.d(TAG, "s = " + s);
result += s;
}
}
} catch (ClientProtocolException e) {
// TODO: handle exception
e.printStackTrace();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
Log.d(TAG, "result = " + result);
Log.d(TAG, "length = " + result.length());
return result;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值