继续搬砖学习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);
}
}