使用HttpClient向服务器端提交数据
2015-12-04 12:25
495 查看
//使用HttpClient向服务器端提交数据 // // HttpClient是apache下的子项目,轻量级的浏览器。 // // 使用步骤: // 1、创建一个浏览器: // 2、输入网址: // 3、按回车,执行请求: // //* 使用GET方式提交数据: // // 代码: //1、创建一个浏览器: HttpClient client = new DefaultHttpClient(); //2、输入网址: HttpGet http = new HttpGet(path); //3、按回车,执行请求: //服务器返回的所有数据都封装到了response里 HttpResponse response = client.execute(http); //得到响应码(状态码) int code = response.getStatusLine().getStatusCode(); if (200 == code) { // 获得服务器端的响应数据 InputStream is = response.getEntity().getContent(); String result = StreamTools.readStream(is); Message msg = Message.obtain(); msg.obj = result; handler.sendMessage(msg); } * 使用POST方式提交数据: new Thread() { public void run() { try { String data = "username=" +URLEncoder.encode(qq,"UTF-8") +"&password="+URLEncoder.encode(pwd,"UTF-8"); // 1、创建一个浏览器: HttpClient client = new DefaultHttpClient(); // 2、输入网址: HttpPost http = new HttpPost(path); //封装提交的参数 BasicNameValuePair value1 = new BasicNameValuePair("username",qq) ; BasicNameValuePair value2 = new BasicNameValuePair("password",pwd) ; List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(value1); parameters.add(value2); //把提交的数据封装到form实体对象中 //默认是iso-8859-1进行url编码,需要显示的指定字符集编码 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,"UTF-8"); //设置提交的数据实体 http.setEntity(entity); // 3、按回车,执行请求: HttpResponse response = client.execute(http); //得到响应码 int code = response.getStatusLine().getStatusCode(); if (200 == code) { // 获得服务器端的响应数据 InputStream is = response.getEntity().getContent(); String result = StreamTools.readStream(is); Message msg = Message.obtain(); msg.obj = result; handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } }; }.start();
相关文章推荐
- TCP、UDP、HTTP、SOCKET之间的区别
- XUtils框架中HttpUtils使用Get请求时总是返回相同信息的问题解决,xutilshttputils
- CentOS 7 网络配置
- http_build_query应用
- iOS获取手机当前的网络状态
- Java 网络学习
- 转:谈谈对Spring IOC的理解 http://www.cnblogs.com/xdp-gacl/p/4249939.html
- 通信协议—HTTP、TCP、UDP
- 关于HTTP协议状态码的问题
- Servelet:HTTP method GET is not supported by this URL
- poj 2584 T-Shirt Gumbo 网络流
- Spring MVC过滤器-HttpPutFormContentFilter
- Apache httpd configuration for IE7 standard mode rendering in IE8(转)——360浏览器兼容模式无法正确展示网页
- Spring MVC过滤器-HiddenHttpMethodFilter
- 嵌入式Linux网络编程(一)
- 常见HTTP状态码
- HTTPS 通信流程(签名、数字证书)
- HTTP 错误405.0 - Method Not Allowed
- 在内部网络为edX配置视频服务
- hdu 4292 Food 网络流