*使用HC( HttpClient )/ UC(HttpURLConnection) 发起网络访问的基本步骤
0.申请权限: 清单配置文件中申请 INTERNET 权限;
1.任何网络访问的相关代码都必须在工作线程进行:
(new AsyncTask/new Thread)启动工作线程
2.创建HC/UC对象
3.声明发起网络访问的方式(GET/POST);
4.进行网络连接
5.获得服务器响应
6.解析服务器响应结果,提取需要的内容,
7.向UI线程提交数据,并在UI线程呈现;
下面以一个向服务器注册的案例对网络访问进行说明
```
//HttpURLConnection进行注册,new Thread启动线程
public static void registUser2(Context context,final User user, final OnRegistFinishListener listener){
//HttpURLConnection进行注册
//启动工作线程
new Thread(){
public void run() {
try {
URL url = new URL("http://172.88.134.145:8080/ems/regist.do");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//声明链接方式 connection.setRequestMethod("POST");
connection.setDoInput(true);//允许接收服务器响应的内容
connection.setDoOutput(true);//允许要向服务器提交内容
//在请求头中,为请求实体中的内容做说明
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//开启链接
connection.connect();
//客户端向服务器提交参数
OutputStream out = connection.getOutputStream();
//true是当缓冲区没有写满的时候强制进行提交,如果不写true,读取完
//毕,缓冲区还没满,她也不会主动提交数据;
PrintWriter pw = new PrintWriter(out, true);
String params = getParams(user);
//客户端需要提交的内容都在params中
pw.print(params);
pw.close();
//客户端获取服务器的响应内容
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();
//在主线程执行
//关联主线程的looper,此方法会在主线程执行,结果才能 //提交到主线程
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
//提交给调用listenter接口的地方, listener.onRegistFinish(result);
}
});
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
```*
<div class="se-preview-section-delimiter"></div>
protected static String getParams(User user) {
Map
protected static String getParams(User user) {
Map<String,String> map = new HashMap<String, String>();
map.put("loginname", user.getName());
map.put("password", user.getPassword());
map.put("realname", user.getRealname());
map.put("email", user.getEmail());
StringBuilder sb = new StringBuilder();
//循环遍历,将键值对转换成服务器识别的字符串;
for(Entry<String, String> entry:map.entrySet()){
sb.append(entry.getKey()).
append("=").
append(entry.getValue()).
append("&");
}
//HttpClient发起网络访问,使用AsyncTask开启工作线程
public static void registUser(Context context, final User user,
final OnRegistFinishListener listener) {
//开启工作线程
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
//创建对象
HttpClient client = new DefaultHttpClient();
//声明方式
HttpPost post = new HttpPost("http://172.88.134.145:8080/ems/regist.do");
//添加一个请求头,对请求实体中的参数做一个说明
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
//在post中添加请求参数
//请求参数会添加在请求实体中
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("loginname", user.getName()));
parameters.add(new BasicNameValuePair("password", user.getPassword()));
parameters.add(new BasicNameValuePair("realname", user.getRealname()));
parameters.add(new BasicNameValuePair("email", user.getEmail()));
//创建请求实体
HttpEntity entity = new UrlEncodedFormEntity(parameters);
post.setEntity(entity);
/发起网络访问并获得网络响应
HttpResponse resp = client.execute(post);
//获得服务器响应的内容
HttpEntity respEntity = resp.getEntity();
//可手动的从流中提取需要的内容,
// InputStream is = respEntity.getContent();
//
//BufferedReader br = new BufferedReader(new //InputStreamReader(is));
//
// String line = br.readLine();
//
// br.close();
//借助系统的工具类提取需要的内内容,比较方便,而且不需要关闭 //流对象,
String line = EntityUtils.toString(respEntity);
return line;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//此方法在UI线程执行,提交结果给UI显示
protected void onPostExecute(String result) {
listener.onRegistFinish(result);
};
}.execute();
}
“`