Android通过Apache HTTP访问HTTP资源
来源:互联网 发布:mac麻醉是怎样的 编辑:程序博客网 时间:2024/04/27 18:33
HttpClient接口
实现类:DefaultHttpClient这也是常用的一个用于实现HttpClient接口的子类,
HttpClietnt中定义的常用抽象方法
方法名称
描述
public abstract HttpResponse execute (HttpUriRequest request)
通过HttpUriRequest对象执行返回一个HttpResponse对象
public abstract HttpResponse execute (HttpUriRequest request, HttpContext context)
通过HttpUriRequest对象和HttpContext对象执行返回一个HttpResponse对象
HttpResponse接口
HttpResponse接口里定义了一系列的set、get方法
方法名称
描述
public abstract HttpEntity getEntity ()
得到一个HttpEntity对象
public abstract StatusLine getStatusLine ()
得到一个StatusLine(也就是HTTP协议中的状态行我们知道HTPP状态行由三部分组成:HTTP协议版本,服务器发回的响应状态代码,状态码的文本描述)接口的实例对象
public abstract Locale getLocale ()
得到Locale对象
….相应的set方法
StatusLine接口
StatusLine接口的常用方法。也可以通过其实现的子类BasicStatusLine类里查看
方法名称
描述
public abstract ProtocolVersion getProtocolVersion ()
得到一个ProtolVersion对象它是一个HTTP版本的封装类,在这个类里定义了一系列的方法我们可以通过它的getProtocol方法取得协议名称,getMinor得到HTPP协议的版本
public abstract String getReasonPhrase ()
状态码的文本描述
public abstract int getStatusCode ()
得到响应状态码
HttpEntity接口
HttpEntity是一个接口
方法名称
描述
public abstract InputStream getContent ()
得到一个输入流对象,我们可以用这个流来操作文件(例如保存文件到SD卡)
public abstract Header getContentType ()
得到Content-Type信息头
public abstract Header getContentEncoding ()
得到Content-Encoding信息头
我们可以通过EntityUtils类,它是一个final类,一个专门针对于处理HttpEntity的帮助类
常用方法
EntityUtils类
EntityUtils类的常用方法
方法名称
描述
public static String getContentCharSet (HttpEntity entity)
设置HttpEntity对象的ContentCharset
public static byte[] toByteArray (HttpEntity entity)
将HttpClient转换成一个字节数组
public static String toString (HttpEntity entity, String defaultCharset)
通过指定的编码方式取得HttpEntity里字符串内容
public static String toString (HttpEntity entity)
取得HttpEntity里字符串内容
NameValuePair
NameValuePair接口是一个简单的封闭的键值对,只提供了一个getName()和一个getValue方法。主要用到的实现类BasicNameVaulePair
HttpGet类
HttpGet它实现了HttpRequest、HttpUriRequest接口
构造方法
方法名称
描述
public HttpGet ()
无参数构造方法用以实例化对象
public HttpGet (URI uri)
通过URI对象构造HttpGet对象
public HttpGet (String uri)
通过指定的uri字符串地址构造实例化HttpGet对象
HttpPost类
同样它也实现了HttpRequest、HttpUriRequest接口等一系列接口
构造方法
方法名称
描述
public HttpPost ()
无参数构造方法用以实例化对象
public HttpPost (URI uri)
通过URI对象构造HttpPost对象
public HttpPost (String uri)
通过指定的uri字符串地址构造实例化HttpPost对象
清楚了上面的所有常用API后,下面我们能过Apache HTTP来访问HTTP资源
三步曲:
1. 创建HttpGet或者HttpPost对象,将要请求的URL对象构造方法传入HttpGet、HttpPost对象
2. 通过HttpClent接口的实现类DefaultClent.的excute(HttpUriRequest request)而我们已经知道HttpGet和HttpPost类都实现了HttpUriRequest接口,所以这里面,我们可以将第1步创建好的HttpGet或者HttpPost对象传入进来。来得到HttpResponse对象
3. 通过HttpResponse取到返回的一些信息,再做提取
实例图片:
帖上一部分源代码:
布局文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent" android:layout_height="wrap_content">
- <TextView android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="url:" />
- <EditText android:id="@+id/urlText" android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="http://10.0.2.2:8080/NetServer/queryServlet?bookId=2" />
- </LinearLayout>
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent" android:layout_height="wrap_content"
- android:gravity="right">
- <Button android:id="@+id/getBtn" android:text="GET请求"
- android:layout_width="wrap_content" android:layout_height="wrap_content" />
- <Button android:id="@+id/postBtn" android:text="POST请求"
- android:layout_width="wrap_content" android:layout_height="wrap_content" />
- </LinearLayout>
- <TextView android:id="@+id/resultView" android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- <LinearLayout android:orientation="horizontal"
- android:layout_width="fill_parent" android:layout_height="wrap_content">
- <TextView android:layout_width="wrap_content"
- android:layout_height="wrap_content" android:text="图片url:" />
- <EditText android:id="@+id/imageurlText" android:layout_width="fill_parent"
- android:layout_height="wrap_content" android:text="http://hiphotos.baidu.com/censhenlu/pic/item/3982b502915ddf9c7a8947c3.jpg" />
- </LinearLayout>
- <Button android:id="@+id/imgBtn" android:text="获取图片"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:layout_gravity="right" />
- <ImageView android:id="@+id/imgeView01"
- android:layout_height="wrap_content" android:layout_width="fill_parent" />
- </LinearLayout>
Java代码:
- package com.jiahui.net;
- import java.io.InputStream;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.StatusLine;
- import org.apache.http.client.HttpClient;
- 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.util.EntityUtils;
- import android.app.Activity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.ImageButton;
- import android.widget.ImageView;
- import android.widget.TextView;
- import android.widget.Toast;
- public class HTTPDemoActivity extends Activity {
- private Button getBtn, postBtn, imageBtn;
- private EditText urlText, imageUrlText;
- private TextView resutlView;
- private ImageView imageView;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- urlText = (EditText) findViewById(R.id.urlText);
- imageUrlText = (EditText) findViewById(R.id.imageurlText);
- resutlView = (TextView) findViewById(R.id.resultView);
- getBtn = (Button) findViewById(R.id.getBtn);
- postBtn = (Button) findViewById(R.id.postBtn);
- imageBtn = (Button) findViewById(R.id.imgBtn);
- imageView = (ImageView) findViewById(R.id.imgeView01);
- getBtn.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- System.out.println(urlText.getText().toString());
- resutlView
- .setText(request("GET", urlText.getText().toString()));
- }
- });
- postBtn.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- System.out.println(urlText.getText().toString());
- resutlView
- .setText(request("POST", urlText.getText().toString()));
- }
- });
- imageBtn.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- getImage(imageUrlText.getText().toString());
- }
- });
- }
- private String request(String method, String url) {
- HttpResponse httpResponse = null;
- StringBuffer result = new StringBuffer();
- try {
- if (method.equals("GET")) {
- // 1.通过url创建HttpGet对象
- HttpGet httpGet = new HttpGet(url);
- // 2.通过DefaultClient的excute方法执行返回一个HttpResponse对象
- HttpClient httpClient = new DefaultHttpClient();
- httpResponse = httpClient.execute(httpGet);
- // 3.取得相关信息
- // 取得HttpEntiy
- HttpEntity httpEntity = httpResponse.getEntity();
- // 得到一些数据
- // 通过EntityUtils并指定编码方式取到返回的数据
- result.append(EntityUtils.toString(httpEntity, "utf-8"));
- //得到StatusLine接口对象
- StatusLine statusLine = httpResponse.getStatusLine();
- //得到协议
- ;
- result.append("协议:" + statusLine.getProtocolVersion() + "\r\n");
- int statusCode = statusLine.getStatusCode();
- result.append("状态码:" + statusCode + "\r\n");
- } else if (method.equals("POST")) {
- // 1.通过url创建HttpGet对象
- HttpPost httpPost = new HttpPost(url);
- // 2.通过DefaultClient的excute方法执行返回一个HttpResponse对象
- HttpClient httpClient = new DefaultHttpClient();
- httpResponse = httpClient.execute(httpPost);
- // 3.取得相关信息
- // 取得HttpEntiy
- HttpEntity httpEntity = httpResponse.getEntity();
- // 得到一些数据
- // 通过EntityUtils并指定编码方式取到返回的数据
- result.append(EntityUtils.toString(httpEntity, "utf-8"));
- StatusLine statusLine = httpResponse.getStatusLine();
- statusLine.getProtocolVersion();
- int statusCode = statusLine.getStatusCode();
- result.append("状态码:" + statusCode + "\r\n");
- }
- } catch (Exception e) {
- Toast.makeText(HTTPDemoActivity.this, "网络连接异常", Toast.LENGTH_LONG)
- .show();
- }
- return result.toString();
- }
- public void getImage(String url) {
- try {
- // 1.通过url创建HttpGet对象
- HttpGet httpGet = new HttpGet(url);
- // 2.通过DefaultClient的excute方法执行返回一个HttpResponse对象
- HttpClient httpClient = new DefaultHttpClient();
- HttpResponse httpResponse = httpClient.execute(httpGet);
- // 3.取得相关信息
- // 取得HttpEntiy
- HttpEntity httpEntity = httpResponse.getEntity();
- // 4.通过HttpEntiy.getContent得到一个输入流
- InputStream inputStream = httpEntity.getContent();
- System.out.println(inputStream.available());
- //通过传入的流再通过Bitmap工厂创建一个Bitmap
- Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
- //设置imageView
- imageView.setImageBitmap(bitmap);
- } catch (Exception e) {
- Toast.makeText(HTTPDemoActivity.this, "网络连接异常", Toast.LENGTH_LONG)
- .show();
- }
- }
- }
开发注意事项:
1.要想访问本地机器不能写成localhost或者127.0.0.1要写成10.0.2.2。这是因为Android模拟器(simulator)把它自己作为了localhost,也就是说,代码中使用localhost或者127.0.0.1来访问,都是访问模拟器自己!若你想在模拟器simulator上面访问你的电脑,那么就使用android内置的IP: 10.0.2.2,10.0.2.2是模拟器设定的特定ip,是你电脑的别名,在模拟器上用10.0.2.2就能成功访问你的电脑本机。
2.记得加上网络访问权限
<uses-permission android:name="android.permission.INTERNET"/>
- Android通过Apache HTTP访问HTTP资源
- Android通过Apache HTTP访问HTTP资源
- 深入Android通过Apache HTTP访问HTTP资源
- 深入Android通过Apache HTTP访问HTTP资源
- 深入Android通过Apache HTTP访问HTTP资源
- 深入Android通过Apache HTTP访问HTTP资源(一)(转)
- 深入Android通过Apache HTTP访问HTTP资源(二)(转)
- 深入Android通过Apache HTTP访问HTTP资源
- 深入Android通过Apache HTTP访问HTTP资源
- Android开发进阶(四)--深入Android通过Apache HTTP访问HTTP资源
- Android 通过http访问服务器
- Android 通过http访问服务器
- Android 通过http访问服务器
- Android 通过http访问服务器
- Android---通过http访问服务器
- 通过http获取资源
- 访问HTTP资源
- 通过HTTP访问2000
- 选择排序
- ffmpeg参数解释
- 使用一台window server 2003主机,管理多台多台子服务器的远程登录
- Linux操作系统中内存buffer和cache的区别 && free 参数说明
- java.util.concurrent.locks.AbstractQueuedSynchronizer构造同步类
- Android通过Apache HTTP访问HTTP资源
- 干巴爹、压灭跌、马杀鸡是什么意思
- Android.mk的用法和基础
- 健康小习惯。
- AOP的理解
- android adb常用指令
- hibernate 由表生成实体类 反向引擎方式
- 安装配置Mysql5.5并且完美解决中文乱码问题
- 关于对list进行排序