zoukankan      html  css  js  c++  java
  • [Android]基于Apache的HttpClient实现

    1. 代码

     /** * 2. 基于Apache接口的HttpClient实现 * org.apache.http.* * * 1.超文本传输协议是互联网上应用最为广泛的一种网络协议 * 2.HTTP是一个客户端和服务器端请求和应答的标准,客户端是终端用户,服务器端是网站 * 3.HTTP是客户端浏览器或其他应用程序与Web服务器之间的应用层通信协议 * * HTTP工作原理 * 1.客户端与服务器建立连接 * 2.建立连接后,客户端想服务器端发送一个请求 * 3.服务器接收到请求之后,向客户端发送响应信息 * 4.客户端与服务器端断开连接 * 注意:这里的第四条需要注意,即当用户看到如下的界面时,客户端就已经与服务器断开连接了。 * * 无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。 * 1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。 * 2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。 * 3.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。 * 如果使用HttpPost方法提交HTTP POST请求,还需要使用HttpPost类的setEntity方法设置请求参数。 * 下面以一个实例介绍这两个方法的具体实现: * 本程序介绍如何通过HttpClient模块来创建Http连接,并分别以Http Get和Post方法传递参数,连接之后取回web server的返回网页结果。 * 注意,在用Post时,传递变量必须用NameValuePais[]数组存储,通过HttpRequest.setEntity()方法来发出http请求。 * 此外,也必须通过DefaultHttpClient().execute(httpRequest)添加HttpRequest对象来接收web server的回复,在通过httpResponse.getEntity()取出回复信息。 * */ package home.lee.httpapache; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import com.example.httpapache.R; import android.app.Activity; import android.os.Bundle; import android.os.StrictMode; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { private static final String URL_PATH1 = "http://www.baidu.com"; private static final String URL_PATH2 = "http://192.168.1.100:9000/00.Java/02.Android/01.Sum/index.html"; //生成一个读入流-用来存储服务器端发送过来的/返回的数据 private InputStream inputStream = null; private HttpResponse httpResponse; private HttpGet httpGet; private String bufferLine = ""; private String contents = ""; private BufferedReader bufferedReader; private EditText result; private Button getFromHttpBtn; private HttpEntity httpEntity; private Header contentType; private StatusLine httpStatusLine; private int httpStatusCode; private Button postFromHttpBtn; protected BasicNameValuePair nameValuePair; protected HttpEntity requestHttpEntity; private HttpPost httpPost; private HttpResponse httpPostResponse; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //for 4.0 up ver. INTERNET permission bug // 详见StrictMode文档 android4verNetworkExceptionMethod(); init(); } private void android4verNetworkExceptionMethod() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } private void init() { result = (EditText)findViewById(R.id.edittext2); getFromHttpBtn = (Button)findViewById(R.id.button1); getFromHttpBtn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { httpClientGetData();//Apache的Get方式 } }); postFromHttpBtn = (Button)findViewById(R.id.button2); postFromHttpBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { httpClientPostData();//Apache的Post方式 } }); } private void httpClientGetData() { contents = ""; //生成一个请求对象-选择服务器域名 httpGet = new HttpGet(URL_PATH1); //生成一个默认Http客户端对象 HttpClient httpClient = new DefaultHttpClient(); try { //客户端执行请求-绑定相关请求-参数为请求对象-接受服务端的响应 httpResponse = httpClient.execute(httpGet); //getEntity()方法获得实体对象-getContent()方法获得数据内容并赋给输入流 httpEntity = httpResponse.getEntity(); httpStatusLine = httpResponse.getStatusLine();//协议和状态码-HTTP/1.1 200 OK httpStatusCode = httpStatusLine.getStatusCode();//状态码-200 System.out.println(httpEntity + "," + httpStatusLine + "," + httpStatusCode); if(httpStatusCode == HttpStatus.SC_OK){ contentType = httpEntity.getContentType(); System.out.println(contentType); inputStream = httpEntity.getContent(); //用BufferedReader读出内容 bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //逐行读取 while((bufferLine = bufferedReader.readLine()) != null){ contents += bufferLine + "
    "; } result.setText(contents); }else { result.setText("Sorry, there is a error at Network and Server Connection!"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } private void httpClientPostData() { contents = ""; /////////////////////////////////////////////////////////////////// //如果传递的参数不止一个,那么就需要用到多个NameValuePair对象 List namValuePairs = new ArrayList(); nameValuePair = new BasicNameValuePair("url", URL_PATH2); namValuePairs.add(nameValuePair); try { //将信息封装到HttpEntity对象中 requestHttpEntity = new UrlEncodedFormEntity(namValuePairs); httpPost = new HttpPost(URL_PATH2); //加载到HttpPost实体中 httpPost.setEntity(requestHttpEntity);//请求中 包含数据 ///////////////////////////////////////////// //生成一个默认Http客户端对象 //////////////////////////////////////////////////////////////////// HttpClient httpClient = new DefaultHttpClient(); httpPostResponse = httpClient.execute(httpPost); inputStream = httpPostResponse.getEntity().getContent(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); while((bufferLine = bufferedReader.readLine()) != null){ contents += bufferLine + "
    "; } result.setText(contents); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 

    2. 效果

    代码下载

  • 相关阅读:
    【★】路由环路大总结!
    自制tunnel口建虚拟专网实验
    自制tunnel口建虚拟专网实验
    自制tunnel口建虚拟专网实验
    常用的组播保留地址列表
    常用的组播保留地址列表
    常用的组播保留地址列表
    程序员经常遇到的几个问题!
    ★路由递归查询方法及相关图示【转载】
    ★路由递归查询方法及相关图示【转载】
  • 原文地址:https://www.cnblogs.com/webapplee/p/3771848.html
Copyright © 2011-2022 走看看