Android中基于HTTP的通信技术(3)使用HttpClient进行Get方式通信

继续搬砖学习android通信(来自极客学院)

使用HttpClient进行Get方式通信,通过HttpClient建立网络链接,使用HttpGet方法读取数据,并且通过Response获取Entity返回值。

package com.example.httpclientget;

import java.io.IOException;

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.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
	private EditText et;
	private TextView text;
	
	HttpClient client;//通过HttpClient建立网络链接

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		client = new DefaultHttpClient();//创建一个默认的client对象
		
		et = (EditText) findViewById(R.id.edtext);
		text = (TextView) findViewById(R.id.textView);
		
		findViewById(R.id.button).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				readNet("http://10.0.2.2:8080/MyWebTest/Do?Name" + et.getText());
			}
		});
		
	}

	public void readNet(String url){
		new AsyncTask<String, Void, String>() {

			@Override
			protected String doInBackground(String... params) {
				String urlString = params[0];
				HttpGet get = new HttpGet(urlString);//获取到的互联网数据
				
				try {
					HttpResponse response = client.execute(get); //execute返回一个 HttpResponse对象
					
					String valString = EntityUtils.toString(response.getEntity());// 通过Response获取Entity返回值。
					
					System.out.println(valString);
					
					return valString;
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return null;
			}
			/*
			 * 实现返回editText中的内容,重写onPostExecute方法
			 */
			@Override
			protected void onPostExecute(String result) {
				text.setText(result);
			}
			
			
		}.execute(url);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值