Http连接请求
来源:互联网 发布:软件开发项目生命周期 编辑:程序博客网 时间:2024/04/30 16:12
一、HttpURLConnection
首先是URL建立一个对象,
URL url=new URL(“http://www.baidu.com”);
然后就是获得
HttpURLConnection connection=url.openConnection();
对connection进行设置即可以有
connection.setRequestMethod()等,参数有GET和POST;
设置连接时间,和阅读时间等
然后就能接收读取到信息
connection.getInputStream()得到InputStream对象然后使用BufferReader的方式再new StringBuilder()保存即可;
如果是POST即为提交数据的 话
即是
得到connection.getOutputStream();
然后DataOutputStream da=new DataOutputStream(OutputStream out);
da.writeBytes(“Username=admin&Pass=12345”);
二、HttpClient
HttpClient client=new DefaultHttpClient();获取HttpClient实例,不能直接创建实例因为HttpClient是一个接口。
HttpGet和HttpPost就是请求方式的两种类型;
HttpGet get=new HttpGet(“http://www.baidu.com”);
Httpclient.execute(get);
HttpPost post=new HttpPost(“http://www.baidu.com“);
提交数据应该先封装数据;
List params=new ArrayList();
params .add(new NameValue(”username“,”admin“));//可见数据时key-value形式;
先把数据封装成entity即编码
UrlEncodeFormEntity entity=new UrlEncodeFormEntity (params,”utf-8“);
post.setEntity(entity);
client.execute(post);
然后执行了execute后会返回HttpResponse对象
HttpResponse httpResponse=client.execute(get);
那么
判断其是否请求和回应都成功即是
if(httpResponse.getStatusLine().getStatusCode()==200)
成功了就能获取数据
HttpEntity entity=httpResponse.getEntity();
String str=EntityUtils.toString(entity,”utf-8”);
注意:
Android studio中6.0后HttpClient已经被移除。
在android 6.0(API 23)中,Google已经移除了移除了Apache HttpClient相关的类
推荐使用HttpUrlConnection,如果要继续使用需要Apache HttpClient,需要在eclipse下libs里添加org.apache.http.legacy.jar,android studio里在相应的module下的build.gradle中加入:
android {
useLibrary ‘org.apache.http.legacy’
}
上面的jar包在:**\android-sdk-windows\platforms\android-23\optional下(需要下载android 6.0的SDK)
- Http连接,发送请求
- Http连接请求
- Http请求连接池
- Http请求连接池
- Http请求连接池
- Http请求连接池
- Http连接GET/POST请求
- Http连接GET/POST请求
- Http请求连接池 - HttpClient 连接池
- java请求http连接(servlet)类
- Http网络请求和连接类型
- Http请求连接池 - HttpClient 的 PoolingHttpClientConnectionManager
- http以及https请求的连接过程
- android HttP请求服务器,连接超时
- http请求过程概述及长连接、短连接简述
- HTTP请求的过程&HTTP/1.0和HTTP/1.1的区别&HTTP怎么处理长连接
- HTTP请求的过程&HTTP/1.0和HTTP/1.1的区别&HTTP怎么处理长连接
- j2ME中对Http同时请求连接的限制
- springmvc4 mybatis 整合 框架源码
- 关于多条件求和
- MVC5+EF6 入门完整教程13 -- 动态生成多级菜单
- python之字符串
- 微信公众平台开发(1)
- Http连接请求
- JNI---在c中使用log 和生成so库
- 大四这一年
- 计算器核心算法代码实现(Java)
- Java设计模式之责任链模式的详解(行为模式)
- 安卓开发之 App Widget
- 广度优先搜索bfs
- 问题:jquery中的change()事件,以及jquery中的prop()事件与attr()事件的区别
- MySQL数据库以及SQL语法基础、中文乱码