Android的http网络请求和发送
原文地址:http://blog.sina.com.cn/s/blog_54ee89d90100np7p.html
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
</manifest>
展现效果:
当然,如果进行正规的HTTP网络请求的调用,有更简单的API来使用,如HTTPClient:
1、使用Map来存储参数
Map<String, String> map = new HashMap<String, String>();
map.put(“name”, “wusheng”);
map.put(“password”, “pwd”);
2、使用DefaultHttpClient创建HttpClient实例
DefaultHttpClient httpClient = new DefaultHttpClient();
3、构建HttpPost
HttpPost post = new HttpPost(“http://wu-sheng.javaeye.com”);
4、将由Map存储的参数转化为键值参数
List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(),
entry.getValue()));
}
5、使用编码构建Post实体
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postData, HTTP.UTF_8);
6、设置Post实体
post.setEntity(entity);
7、执行Post方法
HttpResponse response = httpClient.execute(post);
8、获取返回实体
HttpEntity httpEntity = response.getEntity();
9、将H中返回实体转化为输入流
InputStream is = httpEntity.getContent();
10、读取输入流,即返回文本内容
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = “”;
while((line=br.readLine())!=null){
sb.append(line);
}