方法有两种:
一、HttpClient (apache开发)
二、HttpURLConnection(google在发布安卓时在Java基础上修改得到的)
两种途径的共同步骤:
0. 申请权限 INTERNET访问权限
1. 任何网络访问的相关代码,必须在工作线程中执行!
2. 创建HC/UC对象
3. 声明发起网络访问的方式(GET/POST)
4. 进行网络连接
5. 获得服务器响应的结果
6. 解析结果,提取需要的内容
7. 解析结果要提交到UI线程进行呈现
用两种起工作线程的方法访问网络的实例参考:
No1:
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://xxx/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();
// HttpClient的福利类EntityUtils
String line = EntityUtils.toString(respEntity);
return line;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
listener.onRegistFinish(result);
};
}.execute();
No2:
new Thread(){
public void run() {
try {
URL url = new URL("http://xxxems/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();
PrintWriter pw = new PrintWriter(out, true);
//String params = "loginname="+user.getName()+"&password="+user.getPassword()+"&realname="
// +user.getRealname()+"&email="+user.getEmail();
String params = getParams(user);//getParams(user)的作用同上,
pw.print(params);
pw.close();
//客户端获取服务器的响应内容
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
final String result = br.readLine();
br.close();
//在主线程执行
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
listener.onRegistFinish(result);
}
});
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();