Http访问网络(AsyncTask 异步加载和使用HttpURLConnection)
2015-07-30 19:36
681 查看
两种方式访问百度,并且将服务器所传回的值设置在TextView中。用AsyncTask来实现
一、HttpURLConnection
步骤:
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = url.openConnection();
//此处connection可设置请求方式和连接超时、读取超时的秒数
//connection.setRequestMethod("GET")
InputStream in = connection.getInputStream();
//可以根据输入流来读取数据
connection.disconnnect();
如果想给服务器提交数据:需要将requestedMethod改为POST,并且再获取输入流执之前将要提交的数据写出即可
每条数据以键值对方式存在,数据与数据之间用&隔开
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream("connection.getOutputStream()");
out.writeBytes("username=admin&passwd=123456");
二、HttpClient的方式:
HttpClient是一个接口,因此无法创建它的实例,一般通过DefaultHttpClient来创建实例
步骤:
HttpClient httpClient = new DefaultHttpClient();
//如果发起GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse response =httpClient.execute(httpGet);
执行execute 方法之后,会返回一个HttpResponse对象,服务器返回的信息就会包含在这里面
取服务器返回的状态码,如果等于200,则说明请求和响应都成功了
if(resonse.getStatusLine().getStatusCode()==200){
//首先获得HttpEntity对象
HttpEntity entity = response.getEntity();
//EntityUtils.toString得到最终的结果
String result = EntityUtils.toString(entity,"utf-8");
}
但是,如果是POST请求,则比GET请求稍微麻烦一点
httpPost-->NameValuePair-->BasicNameValuePair--->UrlEncodedFormEntity--->setEntity
//如果发起POST请求
HttpPost httpPost = new HttpPost("http://www.baidu.com");
//通过NameValuePair来存放待提交的数据
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","admin"));
params.add(new BasicNameValurPair("passwd","123"));
//将得到的参数集合传到UrlEncodedFromEntity
UrlEncodedFormEntity entity= new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
之后的步骤就和GET一样 httpClient.execute(httpPost);
BUT,当我在Android studio中基于API 22开发时,会发现用HttpClient ,编译器会提示deprecated,也就是不赞成或者有更好的替代,所以不推荐用HttpClient
布局:
用HttpURLConnection代码:
一、HttpURLConnection
步骤:
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = url.openConnection();
//此处connection可设置请求方式和连接超时、读取超时的秒数
//connection.setRequestMethod("GET")
InputStream in = connection.getInputStream();
//可以根据输入流来读取数据
connection.disconnnect();
如果想给服务器提交数据:需要将requestedMethod改为POST,并且再获取输入流执之前将要提交的数据写出即可
每条数据以键值对方式存在,数据与数据之间用&隔开
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream("connection.getOutputStream()");
out.writeBytes("username=admin&passwd=123456");
二、HttpClient的方式:
HttpClient是一个接口,因此无法创建它的实例,一般通过DefaultHttpClient来创建实例
步骤:
HttpClient httpClient = new DefaultHttpClient();
//如果发起GET请求
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse response =httpClient.execute(httpGet);
执行execute 方法之后,会返回一个HttpResponse对象,服务器返回的信息就会包含在这里面
取服务器返回的状态码,如果等于200,则说明请求和响应都成功了
if(resonse.getStatusLine().getStatusCode()==200){
//首先获得HttpEntity对象
HttpEntity entity = response.getEntity();
//EntityUtils.toString得到最终的结果
String result = EntityUtils.toString(entity,"utf-8");
}
但是,如果是POST请求,则比GET请求稍微麻烦一点
httpPost-->NameValuePair-->BasicNameValuePair--->UrlEncodedFormEntity--->setEntity
//如果发起POST请求
HttpPost httpPost = new HttpPost("http://www.baidu.com");
//通过NameValuePair来存放待提交的数据
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","admin"));
params.add(new BasicNameValurPair("passwd","123"));
//将得到的参数集合传到UrlEncodedFromEntity
UrlEncodedFormEntity entity= new UrlEncodedFormEntity(params,"utf-8");
httpPost.setEntity(entity);
之后的步骤就和GET一样 httpClient.execute(httpPost);
BUT,当我在Android studio中基于API 22开发时,会发现用HttpClient ,编译器会提示deprecated,也就是不赞成或者有更好的替代,所以不推荐用HttpClient
布局:
<ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text" android:text="@string/hello_world" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView>
用HttpURLConnection代码:
String url="http://www.baidu.com" TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView)findViewById(R.id.text); new MyAsyncTask().execute(url); }
//传进去的是String类型的url地址,想得到服务器返回的数据 class MyAsyncTask extends AsyncTask<String,Void,String>{ @Override protected String doInBackground(String... params) { return getDataFromUrl(params[0]); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); mTextView.setText(s); } }
//根据Url获得输入流,之后解析成String类型的数据 public String getDataFromUrl(String url) { HttpURLConnection connection; InputStream is = null; String result = ""; String line =""; try { URL url1 = new URL(url); connection = (HttpURLConnection) url1.openConnection(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line=bufferedReader.readLine())!=null){ result +=line; } } catch (java.io.IOException e) { e.printStackTrace(); } return result; }
相关文章推荐
- HDU 4275 Color the Tree 树的Hash 2012年长春网络赛I题
- http get请求获取服务器返回的应答数据
- select用法详解 http://blog.chinaunix.net/uid-23373524-id-2426940.html
- VS2013 编译libevent 并且使用!
- .net利用ajax返回后台数据时xmlHttp.status=500
- TCP连接的状态与关闭方式及其对Server与Client的影响
- Vmware虚拟机三种网络模式用途
- android 检查网络连接状态实现步骤
- socket网络编程
- Windows批处理:自动检查网络连通性
- .NET手记-HttpClient解析GB2312乱码问题
- nginx后端应用服务器有大量的tcp连接处于time_wait
- 抓包工具Charles (移动开发必备工具, 网络api调试的神器)
- 神经网络模型
- 神经网络模型
- 开源网络库ACE、Boost的ASIO、libevent、libev、ZeroMQ
- angularJs HTTP响应拦截器
- HttpURLConnection及HttpClient选择(转)
- CURL C++网络延时或者最低网速下载设置
- 新博客有了,文章转移到 http://www.iosxxx.com/