Http与HttpClient(已被废弃)通信的介绍,附带一个Http发送GET请求工具类的例子
来源:互联网 发布:知足知不足阅读答案 编辑:程序博客网 时间:2024/06/05 08:45
阅读时如有疑问和错误欢迎评论提出或者加我企鹅1262135886 ,谢谢支持
所谓通信便有发送和接受两种形式,在代码的表现则是POST和GET
以下的URL是笔者随写的,读者根据实际开发进行修改,仅供参考!
*Http的GET请求,得到数据*
第一种方式,开启线程请求数据
package com.example.getposthttp;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import org.apache.http.client.methods.HttpUriRequest;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.provider.ContactsContract.Contacts.Data;import android.view.View;import android.view.View.OnClickListener;public class GetDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_read).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sendRequestWithHttpURLConnection(); } }); } private void sendRequestWithHttpURLConnection() { // 开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { /** * HttpURLConnection代表应用程序和 URL 之间的通信链接。 此类的实例可用于读取和写入此 URL * 引用的资源 */ HttpURLConnection connection = null; try { URL url = new URL("http://www.baidu.com"); // 表示到 URL 所引用的远程对象的连接 connection = (HttpURLConnection) url.openConnection(); // GET从服务器获取数据 connection.setRequestMethod("GET"); // 设置一个指定的超时值(以毫秒为单位),该值将在打开到此 URLConnection // 引用的资源的通信链接时使用。 connection.setConnectTimeout(8000); // 返回读入超时设置 connection.setReadTimeout(8000); // 得到输入流对象 InputStream in = connection.getInputStream(); // 下面对获取到的输入流进行读取 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); StringBuilder respone = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { respone.append(line); } System.out.println(respone.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); }}
第二种方式,使用异步请求数据
package com.example.getposthttp;import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import org.apache.http.client.methods.HttpUriRequest;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.provider.ContactsContract.Contacts.Data;import android.view.View;import android.view.View.OnClickListener;public class GetDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_read).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { try { URL url = new URL(params[0]); try { URLConnection connection = url .openConnection(); InputStream is = connection .getInputStream(); InputStreamReader isr = new InputStreamReader( is, "uft-8"); BufferedReader br = new BufferedReader( isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); isr.close(); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=YouDaoXY&key=659600044&type=data&doctype=json&version=1.1&q=good"); } }); }}
*Http的Post请求,发送数据*
第一种方式:开启线程
package com.example.getposthttp;import java.io.DataOutputStream;import java.net.URL;import java.net.URLConnection;import org.apache.http.client.methods.HttpUriRequest;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.provider.ContactsContract.Contacts.Data;import android.view.View;import android.view.View.OnClickListener;public class GetDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_read).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { sendRequestWithHttpURLConnection(); } }); } private void sendRequestWithHttpURLConnection() { //开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { /** * HttpURLConnection代表应用程序和 URL 之间的通信链接。 * 此类的实例可用于读取和写入此 URL 引用的资源 */ HttpURLConnection connection=null; try { URL url=new URL("http://www.baidu.com"); //表示到 URL 所引用的远程对象的连接 connection=(HttpURLConnection) url.openConnection(); //POST提交数据给服务器 connection.setRequestMethod("POST"); //得到输出流 DataOutputStream out=new DataOutputStream(connection.getOutputStream()); //发送数据 out.writeBytes(""); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); }}
第二种方式:使用异步
package com.example.getposthttp;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.view.View;public class PostDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_read).setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... params) { try { URL url = new URL(params[0]); try { HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setRequestMethod("POST"); // 将此 URLConnection 的 doInput 字段的值设置为指定的值 connection.setDoInput(true); // 将此 URLConnection 的 doOutput 字段的值设置为指定的值。 connection.setDoOutput(true); //得到输出流 OutputStreamWriter osw=new OutputStreamWriter(connection.getOutputStream()); BufferedWriter bw=new BufferedWriter(osw); bw.write("?keyfrom=YouDaoXY&key=659600044&type=data&doctype=json&version=1.1&q=good"); bw.flush(); InputStream is = connection .getInputStream(); InputStreamReader isr = new InputStreamReader( is, "uft-8"); BufferedReader br = new BufferedReader( isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); isr.close(); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }.execute("http://fanyi.youdao.com/openapi.do"); } }); }}
HttpClient的GET请求
public void sendRequestWithHttpClient() { new Thread(new Runnable() { @Override public void run() { try { //获取HttpClient实例,HttpClient是一个接口 HttpClient httpClient=new DefaultHttpClient(); //HttpGet表示发送get请求 HttpGet httpGet=new HttpGet("http://www.baidu.com"); //发送Get请求 HttpResponse httpResponse=httpClient.execute(httpGet); //如果状态码=200 if (httpResponse.getStatusLine().getStatusCode()==200) { //请求和响应都成功了,得到请求实体数据 HttpResponse entity=(HttpResponse) httpResponse.getEntity(); //转换成String类型 String respones=EntityUtils.toString((HttpEntity) entity,"UTF-8"); text.setText(respones); } } catch (Exception e) { // TODO: handle exception } } }); }
*HttpClient的Post请求*
private void ReceiverResponeWithHttpClient() { new Thread(new Runnable() { @Override public void run() { try { //获取HttpClient实例,HttpClient是一个接口 HttpClient httpClient=new DefaultHttpClient(); //HttpGPost表示发送Post请求 HttpPost httpPost=new HttpPost("http://www.baidu.com"); //NameValuePair将某一名称与一个属性为 IDL struct 的值关联,并在 DynStruct API 中使用。 //简单点的意思就是键值对的意思,前面是键,后面是值 List<NameValuePair> params=new ArrayList<NameValuePair>(); //以键值对的形式添加 params.add(new BasicNameValuePair("username", "adaim")); params.add(new BasicNameValuePair("password", "123456")); //UrlEncodedFormEntity这个类是用来把输入的数据编码成合适的数据 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"uft-8"); httpPost.setEntity(entity); HttpResponse httpResponse=httpClient.execute(httpPost); } catch (Exception e) { // TODO: handle exception } } }); }
到这里Http与HttpClient已经介绍完了
由于一个项目可能很多地方会用到GET和POST请求,我们不可能每次都去重复写一次,所以我们一般会去写个工具类,下面是我写的一个Http发送GET请求工具类的例子,希望读者能够举一反三,下面用到了回调机制,回调机制的用法及其作用读者可以自行研究一下,这里就不介绍了。
首先定义一个回调接口
package com.example.getposthttp;public interface HttpCallBackListener { void onFinish(String respones); void onError(Exception e);}
package com.example.getposthttp;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;/** * 回调机制 * @author Administrator * */public class HttpUtil { private static void sendRequestWithHttpURLConnection(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(); // GET从服务器获取数据 connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); connection.setDoInput(true); connection.setDoOutput(true); InputStream in = connection.getInputStream(); // 下面对获取到的输入流进行读取 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); StringBuilder respone = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { respone.append(line); } if (listener!=null) { //回调onFinish方法 listener.onFinish(respone.toString()); } } catch (Exception e) { if (listener!=null) { //回调onError方法 listener.onError(e); } }finally{ if (connection!=null) { connection.disconnect(); } } } }).start(); }}
*谢谢观看,欢迎转载*
0 0
- Http与HttpClient(已被废弃)通信的介绍,附带一个Http发送GET请求工具类的例子
- Http与HttpClient(已被废弃)通信的介绍,附带一个Http发送GET请求工具类的例子
- httpClient 用于发送HTTP请求的工具类
- httpClient 用于发送HTTP请求的工具类
- java使用HttpClient模拟发送http的get、post请求
- java发送http的get、post请求工具类
- 用HttpClient发送get,post请求的工具类
- Apache 大三方法HTTP请求链接响应之HttpClient的GET和POST工具类封装
- HttpClient 发送GET和POST请求(HTTP)
- 异步的HTTP POST与GET请求例子
- 异步的HTTP POST与GET请求例子
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- http发送get请求的总结
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- 发送Http请求(POST GET)的方法
- java发送http的get、post请求
- BUG:android.content.res.Resource$NotFoundException:String resource ID #0X0
- php 限制输入文字
- BZOJ 1800 [Ahoi2009]fly 飞行棋
- 数据库SQL优化大总结
- 32. Longest Valid Parentheses
- Http与HttpClient(已被废弃)通信的介绍,附带一个Http发送GET请求工具类的例子
- Python定时任务框架APScheduler
- linux开放指定端口
- 华为:用一个圈子联接一个圈子
- Xcode 8 新特性
- ACE介绍及简单服务器实例
- 好的代码组织方式只是为了更好看吗?
- php+ajax实现跨域单点登录
- 手把手教你做智能LED灯(三) 手机控制端开发