1. 程式人生 > >Android中基於HTTP的通訊技術(3)使用HttpClient進行Get方式通訊

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);
	}
}