HttpClient
来源:互联网 发布:金庸对悟空传评价知乎 编辑:程序博客网 时间:2024/06/06 01:18
//请求网络(耗时操作)在子线程中进行
更新UI 用Handler runOnUiThread view.post(new RUnnable(){ "更新UI" })等
在API 23中,Google已经移除了移除了Apache HttpClient相关的类 。谷歌推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,有两种方法。
1.Eclipse下libs里添加org.apache.http.legacy.jar
2.studio中的build.gradle
android { useLibrary 'org.apache.http.legacy' }
//get请求**************
public void doGet(){
StringBuffer result=new String Buffer();
//创建HttpClient对象,打开一个浏览器
HttpClient httpClient=new DefaultHttpClient();
//创建HttpGet对象 ,get请求的对象
HttpGet httpGet=new HttpGet(URL);
try{
//发起请求 走起! 拿到responseduixaing 也是服务器响应的对象
HttpResponse httpResponse= httpClient.execute(httpGet);
//还要根据相应行,拿到响应码 /**
int responseCode=httpResponse.getStatusLine().getStatusCode(); //响应码
if(200==responseCode){
//请求成功
HttpEntity entity=httpResponse.getEntity(); //拿到实体对象
InputStream in=entity.getContent();//返回的数据就是字符流
//缓冲流 包含转换流 字节转成字符
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
}catch(){}
}
//post请求 ****************
putblic void dopost(){
String result = null;
HttpClient client=new DefaultHttpClient();//先拿到对象
HttpPost httpPost=new HttpPost(POSTURL);
try{
//封装参数的集合
List<NameValuePair> parameters=new ArrayList<NameValuePair>();
//这个集合就是添加要传递的参数
parameters.add(new BasicNameValuePair("key",key)); //集合存放对象
parameters.add(new BasicNameValuePair("type",type));
//创建传递参数封装实体对象
UrlEncodedFormEntity encodeEntity=new UrlEncodeFormEntity(parameters,"UTF-8");//设置传递参数
///把实体对象存入到httpPost对象中 这一步很重要 post请求需要把集合实体对象添加进去 UrlEncodeFromEntity
httpPost.setEntity(encodeEntity);
//调用第一步中创建好的实例的 execute方法 这一步操作是和get一样 发起请求了 浏览器
HttpResponse response=client.execute(httpPost);//发送 走~
//然后一样的操作 拿到响应码
int responseCode response=response.getStatusLine().getStatusCode();//响应码
response_msg = response.getStatusLine().getReasonPhrase();//返回内容
if(200==responseCode){
//得到返回的实体对象
HttpEntity entity=response.getEntity();//返回的实体ENtity对象
InputStream in= entity.getContent();//拿到输入流
//接收消息
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
int length = 0;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) != -1) {
byteOut.write(buffer, 0, length);
}
}
}
}
//更新UI线程
ImageView.post(new Runnable() {
@Override
public void run() {
ImageView.setImageBitmap(bitmap);
}
});
- HttpClient
- HttpClient
- httpClient
- HttpClient
- HttpClient
- HttpClient
- HttpClient
- HttpClient
- HttpClient
- HttpClient
- HttpClient
- httpclient
- httpclient
- HttpClient
- HttpClient
- httpclient
- httpclient
- HttpClient
- 域服务篇 02. 域服务配置 ❀ Windows Server 2016
- [NOIP模拟赛]相似字符串
- 使用行为树(Behavior Tree)实现游戏AI
- RecyclerView中使用CheckBox勾选混乱问题解决以及单选功能的实现
- 数据库的增删改查
- HttpClient
- BUAA OJ 94 双层汉诺塔
- linux定时任务的设置 crontab 配置指南
- Gossiping闲聊路由协议
- 二维数组中的查找、空格替换、从尾到头打印链表 --漫漫算法路 刷题篇
- 微信开发----群发接口
- python
- java多线程(三)Synchronized
- 文章标题