使用HTTP访问网络
来源:互联网 发布:php三个字符加一个点 编辑:程序博客网 时间:2024/06/06 00:56
1、使用HttpURLConnection
package com.example.httpurlconnectiontest;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;/** * 发送HTTP请求模板代码 * * @author Administrator * */public class HttpUrlConnectionUtil { public static void sendHttpRequest(final String address, final HttpCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL url = new URL(address); // 获取实例 connection = (HttpURLConnection) url.openConnection(); // 设置请求方式 connection.setRequestMethod("GET"); // 如果为POST方式 // connection.setRequestMethod("POST"); // DataOutputStream out = new // DataOutputStream(connection.getOutputStream()); // out.writeBytes("username=admin&password=123456"); // 设置连接超时 connection.setConnectTimeout(5000); // 设置读取超时 connection.setReadTimeout(5000); // 是否可读可写 connection.setDoInput(true); connection.setDoOutput(true); // 获取服务器返回的输入流 InputStream in = connection.getInputStream(); // 对输入流进行读取 BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } if (listener != null) { // 回调onFinish()方法 listener.onFinish(response.toString()); } } catch (Exception e) { if (listener != null) { // 回调onErrorr()方法 listener.onError(e); } } finally { if (connection != null) { // 将这个HTTP连接关闭掉 connection.disconnect(); } } } }).start(); } public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }}
调用的时候使用的模板代码:
String address = "http://www.baidu.com"; HttpUrlConnectionUtil.sendHttpRequest(address, new HttpCallbackListener() { @Override public void onFinish(String response) { // 在这里根据返回内容执行具体的逻辑 } @Override public void onError(Exception e) { // 在这里对异常情况进行处理 } });
不要忘记权限
<uses-permission android:name="android.permission.INTERNET"/>
2、使用HttpClient:
HttpClient是Apache提供的HTTP网络访问接口。
The type HttpClient is deprecated,官方已经不推荐使用了。
HttpClient的API数量众多,Android团队在提升和优化HttpClient方面的工作态度并不积极。
新的API样例:
DefaultHttpClient–>CloseableHttpClient
HttpResponse–>CloseableHttpResponse
所以用HttpURLConnection就够了。
0 0
- 使用HTTP访问网络
- 使用Http访问网络
- 使用HTTP协议访问网络
- 使用HTTP协议访问网络
- 使用HTTP协议访问网络
- 使用HTTP协议访问网络
- 使用Http协议访问网络
- 使用http协议访问网络
- 使用HTTP协议访问网络
- 使用 HTTP协议访问网络
- Android使用Http访问网络
- 使用Http访问网络(使用Apache HttpClient)
- Android学习使用HTTP协议访问网络
- Android之使用HTTP协议访问网络
- Android使用HTTP协议访问网络
- Android使用Http协议访问网络
- 怎样使用HTTP协议访问网络
- Android使用Http协议访问网络
- 稳定排序和不稳定排序
- Nginx 反向代理、负载均衡、页面缓存、URL重写及读写分离详解
- 对通信模型的疑惑
- vim复制文件内容
- OpenFST notes
- 使用HTTP访问网络
- 2015年,我的创业记忆片段
- LeetCode 145:Binary Tree Postorder Traversal
- linux内核ipv4网络部分分层结构及涉入源文件
- 观察者模式
- 唐纳德.霍尔《是时候了》
- swift中的协议
- 算法设计题2.25-线性表-第2章-《数据结构习题集》-严蔚敏吴伟民版
- 大话设计模式之外观模式(Java版实现) 买股票还是买基金在此揭晓