Android中Apache包介绍

Apache包是对android联网访问封装的很好的一个包,也是android访问网络最常用的类。

下面分别讲一下怎么用HttpClient实现get,post请求。

1.Get 请求

HttpGet get = new HttpGet("http://www.baidu.com");

HttpClient hClient = new DefaultHttpClient();

httpResponse = hClient.execute(get);

2.Post 请求

Map<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("permission", String.valueOf(permission));

 List<NameValuePair> list = new ArrayList<NameValuePair>();
 if(map != null && !map.isEmpty()){
 for(Map.Entry<String, String> entry : map.entrySet()){//迭代器
 //键值对
 NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
 list.add(nameValuePair);
 }
 }

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);
//使用post方式提交数据
HttpPost post = new HttpPost(path);
post.setEntity(entity);//请求体中
//默认客户端
HttpClient client = httpClient;

HttpResponse httpResponse = client.execute(post);

3.代码实例:

先是get请求

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	private Button requestButton;
	private HttpResponse httpResponse;
	private HttpEntity entity;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		requestButton = (Button) findViewById(R.id.requestButton);
		
		requestButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
		         new Thread(new Downtest()).start();
			}
		});
	}
   class Downtest implements Runnable{

	  public void run() {
		//生成一个请求对象,请求
			HttpGet get = new HttpGet("http://www.baidu.com");
			//生成一个Http客户端对象
			HttpClient hClient = new DefaultHttpClient();
			//使用Http客户端发送请求对象
			InputStream inputStream = null;
			try {
				httpResponse = hClient.execute(get);//httpResponse返回的响应
              //返回的响应数据就放在里边				
				entity = httpResponse.getEntity();
				inputStream = entity.getContent();
			    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
			    String result = "";
			    String line = "";
			   while((line = reader.readLine())!= null){
				   result = result+ line;
			   }
			   System.out.println(result);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try{
					inputStream.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
	 }
   } 
   
}
再是post请求

public class AccountHttpUtils {

	//private static String PATH = "http://192.168.253.1:8088/CallName/servlet/AccountServler";
    private static HttpClient httpClient;
	public AccountHttpUtils(HttpClient httpClient) {
           this.httpClient = httpClient;
	}
   public static String sendHttpClient(String path,Map<String,String> map,String encode){
	  List<NameValuePair> list = new ArrayList<NameValuePair>();
	  if(map != null && !map.isEmpty()){
		  for(Map.Entry<String, String> entry : map.entrySet()){//迭代器
			  //键值对
			  NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
			  list.add(nameValuePair);
		  }
	  }
	  try {
		  //实现将请求的参数封装到表单中,
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);
		//使用post方式提交数据
		HttpPost post = new HttpPost(path);
		post.setEntity(entity);//请求体中
		//默认客户端
		HttpClient client = httpClient;
		
		HttpResponse httpResponse = client.execute(post);
		if(httpResponse.getStatusLine().getStatusCode() == 200){
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream inputStream = httpEntity.getContent();
			return changeInputeStream(inputStream, encode);
		}
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 
	   return "";
   }
   /**
    * 将一个输入流转换成字符串
    * @param inputStream
    * @param encode
    * @return
    */
   private static String changeInputeStream(InputStream inputStream,String encode) {
       //通常叫做内存流,写在内存中的
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if(inputStream != null){
			try {
				while((len = inputStream.read(data))!=-1){
					data.toString();
					outputStream.write(data, 0, len);
				}
				//result是在服务器端设置的doPost函数中的
				result = new String(outputStream.toByteArray(),encode);
				outputStream.flush();
				outputStream.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
	public static String set(String id,String name,int permission) {
		// TODO Auto-generated method stub
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		map.put("name", name);
		map.put("permission", String.valueOf(permission));
		String result = AccountHttpUtils.sendHttpClient(AbstractHttpUtils.PATH+"servlet/AccountServler", map, "utf-8");
		System.out.println("result:"+ result);
		return result;
	}

}

4.get请求访问的是百度,返回的是百度首页的源代码

post是我的一个小项目中的类

不过结构已经很清晰啦。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache Android是指Apache软件基金开发和维护的与Android操作系统相关的项目和工具。 首先,Apache是一个非营利性的组织,致力于开发和维护开源软件项目。Apache基金的使命是通过提供开放、稳定、安全的软件来推动计算机技术的发展。Apache是世界上最大的开源组织之一,拥有众多的顶级项目。 Android是由Google开发的一个基于Linux的开源移动操作系统。它在全球范围内被广泛应用于智能手机、平板电脑和其他移动设备上。由于其开放的性质,Android吸引了很多开发者和社区的参与。 Apache Android项目涉及到一系列与Android相关的工具和框架。其最有名的就是Apache Cordova(原PhoneGap),它是一个开源的移动应用开发框架。Cordova允许开发人员使用HTML、CSS和JavaScript等前端技术来构建跨平台的移动应用程序。通过Cordova,开发者可以将应用程序打为原生的Android应用,并可以在其他平台上运行,如iOS和Windows。 除了Cordova,Apache还有其他与Android相关的项目,如Apache Kafka和Apache Flink等。这些项目提供了一些用于数据处理和分发的工具和框架,使开发者能够更好地在Android设备上进行数据分析和处理。 总之,Apache AndroidApache基金开发的一系列与Android操作系统相关的项目和工具,旨在提供开源的、跨平台的移动应用开发和数据处理解决方案。这些项目的存在为开发者提供了更多选择和机,促进了Android生态系统的发展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值