HttpClient的使用与java中使用是一样的。先用Get方法来说:
1.创建一个异步线程(AsyncTask)用来进行网络连接
2.使用DefaultHttpClient来创建一个HttpClient,
HttpClient client = new DefaultHttpClient(); //生成client
3.设置为Get方法。
HttpGet get = new HttpGet(urlString);//设置为get方法
后边的与Java中一样
public class HttpClientActivity extends AppCompatActivity implements View.OnClickListener{
private Button mBtnHttpClientDoGet;
private Button mBtnHttpClientDoPost;
private TextView mTextViewHttpClientDoGet;
private TextView mTextViewHttpClientDoPost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_client);
mBtnHttpClientDoGet = (Button) findViewById(R.id.button_httpclient_doget);
mBtnHttpClientDoPost = (Button) findViewById(R.id.button_httpclient_dopost);
mTextViewHttpClientDoGet = (TextView) findViewById(R.id.textview_httpclient_doget);
mTextViewHttpClientDoPost = (TextView) findViewById(R.id.textview_httpclient_dopost);
mBtnHttpClientDoGet.setOnClickListener(this);
mBtnHttpClientDoPost.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_httpclient_doget:
MyAsyncTaskDoGet task = new MyAsyncTaskDoGet();
task.execute("");
break;
case R.id.button_httpclient_dopost:
break;
default:
break;
}
}
class MyAsyncTaskDoGet extends AsyncTask<String,String,String>{
String line = "";
@Override
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient(); //生成client
String urlString = "http://192.168.***.**:8080/HTTpTest_Servelet/ServeletTest?username=zhangsan";
HttpGet get = new HttpGet(urlString);//设置为get方法
get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设定服务器接收后数据的读取方式为utf-8
try {
HttpResponse response = client.execute(get);//执行
StatusLine statusLine = response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
int code = statusLine.getStatusCode();//得到http的状态码
if (code== HttpURLConnection.HTTP_OK) {
HttpEntity entity = response.getEntity();//得到返回数据的实体
InputStream is = entity.getContent();//得到输入流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
line = br.readLine();
StringBuffer buffer = new StringBuffer();
while(line!=null){
System.out.println(line);
buffer.append(line);
line = br.readLine();
}
publishProgress(buffer.toString().trim());//将读取到的数据传递到onProgressUpdate上
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//执行get方法,得到服务器返回的所有数据
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
mTextViewHttpClientDoGet.setText(values[0]);//将传过来的数据设置到文本上
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
}