android网络连接之httpclient
2016-07-14 16:17
543 查看
//get请求方式 public void dianji(View view) { String path = "http://jsjtest.applinzi.com/one.php?name="+
+URLEncoder.encode("name")+"&pass="+"pass";//使用HttpClient框架做get方式提交
//首先创建HttpClient客户端对象
HttpClient hc = new DefaultHttpClient();
//创建HttpGet对象
HttpGet hg = new HttpGet(path);
//使用客户端对象将get请求发送出去
try {
HttpResponse rs = hc.execute(hg);
StatusLine sl = rs.getStatusLine();
//响应头的状态行
if (sl.getStatusCode() == 200) {
//响应头的实体
HttpEntity entity = rs.getEntity();
//实体的内容是服务器输入流
InputStream is = entity.getContent();
String content = getTextFromStream(is);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//此方法读出服务器流返回的字符串
public String getTextFromStream(InputStream is) {
byte[] b = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
}
String text = new String(bos.toByteArray());
bos.close();
return text;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//post请求方式
public void dianji(View view) { String path = "http://jsjtest.applinzi.com/one.php"; //使用HttpClient框架做post方式提交 //首先创建HttpClient客户端对象 HttpClient hc = new DefaultHttpClient(); //创建HttpPost对象 HttpPost hp = new HttpPost(path); //设置post请求对象的实体,也就是把提交的数据封装到post请求的输出流中 BasicNameValuePair bnvp = new BasicNameValuePair("name", "名字"); BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", "密码"); List<BasicNameValuePair> list = new ArrayList<>(); list.add(bnvp); list.add(bnvp2); UrlEncodedFormEntity uef = null; try { uef = new UrlEncodedFormEntity(list, "utf-8"); hp.setEntity(uef); HttpResponse hr = hc.execute(hp); if(hr.getStatusLine().getStatusCode()==200){ InputStream is=hr.getEntity().getContent(); String text=getTextFromStream(is); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }//不要忘了在清单文件中写入网络权限
相关文章推荐
- HDU 3605 网络流
- webservice-httpd
- CentOS 平台,使用 httpd 2.2 和 httpd 2.4 部署 web服务器
- Windows下C语言的Socket编程例子(TCP和UDP)
- android中图片的三级缓存cache策略(内存/文件/网络)
- httpd.conf服务器配置简单介绍
- TCP协议
- http header详解
- TCP连接心跳机制
- httpd-2.2 常用配置选项及VirtualHost
- HTTP: POST PUT
- 【记录】详解HTTP GET请求
- HTTP协议的请求与响应
- asp.net HTTP请求过程
- HTTPS通信中的身份认证机制
- 应用测试中的弱网络模拟测试-微信测试工程师手把手教程
- http status 500 unable to compile classes for jsp
- 网络请求_Http协议详解
- 调用caffe进行网络训练(caffe.cpp 解析)
- 使用Live555类库实现的网络直播系统