Android使用http协议与服务器通信流程
HTTP通信类,HttpURLConnection和HttpClient。我这里采用的是HttpClient
以下代码是我在APP应用中修改密码
new Thread() {
public void run() {
String context;
String path = "http://你的服务器ip/public/index.php/index/yanzmreg";
//传递服务端需要的参数
Map<String, String> params = new HashMap<>();
params.put("userName", username);
params.put("password", pwd);
try {
//path请求网址,params传递的参数
context = HttpUtil.httpPost2(path, params, SetMMActivity.this);
//获取返回值
JSONObject jsonObject = new JSONObject(context);
int status = jsonObject.getInt("status");
String msg = jsonObject.getString("msg");
//判断是否请求成功,status=1成功,否则失败
if (status==1) {
//请求成功操作
//获取请求成功的返回值
String data = jsonObject.getString("data");
Gson gson = new Gson();
Map<String, Object> map = new HashMap<String, Object>();
map = gson.fromJson(data, map.getClass());
id = ((Double) map.get("id")).intValue();
······
}else{
//请求失败提示
Looper.prepare();
showToast(msg);
Looper.loop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
这里是封装的一个网络请求工具类,为了避免报错,除了请求正常并且成功的返回值其他的我都是采用提示网络请求失败
public static String httpPost2(String path, Map<String, String> params, Context context) throws Exception {
String content = null;
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
HttpParams params1 = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params1, 10000); //设置连接超时
HttpConnectionParams.setSoTimeout(params1, 10000); //设置请求超时
DefaultHttpClient client = new DefaultHttpClient(params1);
// DefaultHttpClient client = new DefaultHttpClient();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) { //Map改为对象
if (entry != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
} else {
return null;
}
}
}
HttpPost post = new HttpPost(path);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, "UTF-8");
// 准备post方式提交正文 以实体形式准备(建值对形式)
post.setEntity(entity);
// 执行一个get请求
HttpResponse response = client.execute(post);
//获取服务器的返回状态码
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
//获取服务器返回数据 以流的形式返回
InputStream inputStream = response.getEntity().getContent();
// 把流转换成字符串
content = StreamTools.readStream(inputStream);
//因为有时候返回的是null,所以在这里做了一下返回值的长度判断
if (content.length() < 5) {
return "{status:no,msg:网络异常}";
}
return content;
} else {
return "{status:no,msg:网络异常}";
}
}
}
每次需要发送http请求时,都开一个子线程用于发送请求,子线程中接收到结果或抛出异常时,根据情况给UI线程发送message,最后在UI线程的handler的handleMessage方法中做结果解析和UI更新。