凡是接触过android应用开发的,都离不开网络编程,android应用作为一个客户端,没有了服务端的服务是没多大作为的,要跟服务端交互,必须要用到网络编程,就我接触来说,android的网络编程有三种方法。
方法一、利用httpurlconnection,用法如下
利用HttpURLConnection对象,我们可以向网络发送请求参数.
String requestUrl = http://localhost:8080/itcast/contanctmanage.do;
Map<String, String> requestParams = new HashMap<String, String>();
requestParams.put("age", "12");
requestParams.put("name", "中国");
StringBuilder params = new StringBuilder();
for(Map.Entry<String, String> entry : requestParams.entrySet()){
params.append(entry.getKey());
params.append("=");
params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
params.append("&");
}
if (params.length() > 0) params.deleteCharAt(params.length() - 1);
byte[] data = params.toString().getBytes();
URL realUrl = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
conn.setDoOutput(true);//发送POST请求必须设置允许输出
conn.setUseCaches(false);//不使用Cache
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(data);
outStream.flush
方法二、利用httpclient,用法如下,传参数
HttpClient client = new DefaultHttpClient(); //创建一个HttpClient
HttpPost request = new HttpPost(); //实例化新的Http方法
request.setURI(new URI("http://code.google.com/android/")); // 设置HTTP参数
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuepair("one","valueGoesHere"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);//使用httpClient执行HTTP调用
BufferedReader in = new BufferedReader(new InputSteamReader(response.getEntity.getContent));//处理HTTP响应
方法三,利用androidhttpclient
经过实际项目,利用方法一的时候,第一连接服务器,在connect的时候,要花比较长的时间,
而方法二在连接服务器时,速度比较快,网络好时,3秒就连接上,
强力推荐用方法二,HttpClient。
1169

被折叠的 条评论
为什么被折叠?



