Android学习(51) -- 使用HttpClient框架做GET提交
2016-05-23 23:49
627 查看
发送get请求
创建一个客户端对象HttpClient client = new DefaultHttpClient();
创建一个get请求对象
HttpGet hg = new HttpGet(path);
发送get请求,建立连接,返回响应头对象
HttpResponse hr = hc.execute(hg);
获取状态行对象,获取状态码,如果为200则说明请求成功
if(hr.getStatusLine().getStatusCode() == 200){ //拿到服务器返回的输入流 InputStream is = hr.getEntity().getContent(); String text = Utils.getTextFromStream(is); }
代码
public void get(View v){ EditText et_name = (EditText) findViewById(R.id.et_name); EditText et_pass = (EditText) findViewById(R.id.et_pass); final String name = et_name.getText().toString(); final String pass = et_pass.getText().toString(); Thread t = new Thread(){ @Override public void run() { String path = "http://192.168.1.130/Web/servlet/CheckLogin?name=" + URLEncoder.encode(name) + "&pass=" + pass; //使用httpClient框架做get方式提交 //1.创建HttpClient对象 HttpClient hc = new DefaultHttpClient(); //2.创建httpGet对象,构造方法的参数就是网址 HttpGet hg = new HttpGet(path); //3.使用客户端对象,把get请求对象发送出去 try { HttpResponse hr = hc.execute(hg); //拿到响应头中的状态行 StatusLine sl = hr.getStatusLine(); if(sl.getStatusCode() == 200){ //拿到响应头的实体 HttpEntity he = hr.getEntity(); //拿到实体中的内容,其实就是服务器返回的输入流 InputStream is = he.getContent(); String text = Utils.getTextFromStream(is); //发送消息,让主线程刷新ui显示text Message msg = handler.obtainMessage(); msg.obj = text; handler.sendMessage(msg); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; t.start(); } public class Utils { public static 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) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
相关文章推荐
- HTTP Authorization
- 网络安全实验室基础关 writeup
- python网络爬虫学习(三)正则表达式的使用之re.match方法
- C#中调用Matlab人工神经网络算法实现手写数字识别
- 采用发消息的形式查看网络图片
- 关于浏览器和网络的20项须知
- Android_Async_Http(1)—get请求和带参数请求
- 关于浏览器和网络的20项须知-前言
- cs231n 卷积神经网络与计算机视觉 1 基础梳理与KNN图像分类
- Atitit.http连接合并组件 ConnReducerV3 新特性
- Atitit.http连接合并组件 ConnReducerV3 新特性
- Atitit.http连接合并组件 ConnReducerV3 新特性
- TCP/IP学习笔记
- java网络编程—TCP(1)
- java网络编程—TCP(1)
- Nginx + Tomcat + HTTPS 配置不需要在 Tomcat 上启用 SSL 支持 3ff8
- 网络编程之Json解析方式与Gson方式解析两兄弟的行为和特点
- Centos 6.5 本地局域网基于HTTP搭建YUM
- 最新xmlns:android="http://schemas.android.com/apk/res/android"的理解
- BP神经网络