Android HttpClient 和 HttpURLConnection 的使用

本文介绍了在Android中使用HttpClient和HttpURLConnection两种方式发送HTTP请求的具体实现方法。通过示例代码展示了如何进行GET请求,并处理响应结果。

在Android上发送HTTP的请求一般有两种方式。分别是HttpClient 和HttpURLConnection。下面对这两个方法的实现说明一下。


httpClient 

首先布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".HttpClientActivity" >

   <TextView
        android:id="@+id/TeViewCon_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

java代码

package com.example.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class HttpClientActivity extends Activity {

	private TextView tView ;
	StringBuffer content = new StringBuffer() ;
	String cont ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_client);
        
        tView = (TextView) findViewById(R.id.TeViewCon_ID) ;
        HttpClientAsyncTask myAsyncTask = new HttpClientAsyncTask() ;
        myAsyncTask.execute("a") ;
    }
    
    public class HttpClientAsyncTask extends AsyncTask<String, Integer, String>{

		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			try {
				HttpClient httpClient = new DefaultHttpClient() ;
				HttpGet httpGet = new HttpGet("http://www.baidu.com") ;
				HttpResponse httpResponse = httpClient.execute(httpGet) ;
				if(httpResponse.getStatusLine().getStatusCode()==200){
					HttpEntity entity = httpResponse.getEntity() ;
					cont = EntityUtils.toString(entity,"utf-8") ;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace() ;
			}			
			return cont;
		}
		
		@Override
		protected void onPostExecute(String str){
			tView.setText(str) ;
		}
    	
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.http_client, menu);
        return true;
    }
    
}


HttpURLConnection

布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".HttpURLConnectionActivity" >

    <TextView
        android:id="@+id/TeViewCon_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>
java代码

package com.example.httpurlconnection;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

public class HttpURLConnectionActivity extends Activity {
	
	private String strURL = "http://www.baidu.com/" ;
	private TextView tViews ;
	StringBuilder content = new StringBuilder();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_urlconnection);
     
        tViews = (TextView) findViewById(R.id.TeViewCon_ID) ;
        HttpURLAsyncTask myAstask = new HttpURLAsyncTask(tViews) ;
        myAstask.execute(strURL) ;
    }

    public class HttpURLAsyncTask extends AsyncTask<String,Integer,String>{
    	
    	private TextView tView ;
    	public HttpURLAsyncTask(TextView tView){
    		this.tView = tView ;
    	}
    	
		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub		
			
			try {
				URL url =new URL(arg0[0]) ;
				HttpURLConnection connection =(HttpURLConnection) url.openConnection() ;
				//服务器的常用的两个方法,post,get
				connection.setRequestMethod("GET") ;
				//链接超时,读取超时,根据自己情况定
				connection.setConnectTimeout(8000) ;
				connection.setReadTimeout(8000) ;
				//下面是读取,可以用connection带的方法,获取输入流
				InputStream inStream = connection.getInputStream() ;
				BufferedReader reader = new BufferedReader(new InputStreamReader(inStream)) ; 
				String line ;
				while( (line=reader.readLine()) != null ){
					content.append(line) ;
				}				
				reader.close() ;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
			return content.toString();
		}
    	@Override
    	protected void onPostExecute(String str){
        	tView.setText(str) ;
        }
    } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.http_urlconnection, menu);
        return true;
    }
    
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值