在Android開發中,不可避免的會用到網絡連接,而網絡連接是用到Http協議來發送和接受數據,Android中有用到了兩種方式來進行Http通信,HttpURLConnection和HttpClient,HttpURLConnection在上一篇中已經給出,這裏再給出HttpClient的通信方式。
HttpClient中有兩種方法,DoGet和DoPost方法。
package com.example.administrator.networkdemo;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by Administrator on 2015/9/13.
*/
public class HttpClientActivity extends Activity implements View.OnClickListener {
private Button mButtonDoget;
private Button mButtonDopost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_httpclient);
mButtonDoget = (Button) findViewById(R.id.httpclient_doget);
mButtonDoget.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.httpclient_doget:
MyDoGetAsyncTask task = new MyDoGetAsyncTask();
task.execute();
break;
case R.id.httpclient_dopost:
MyDoPstAsyncTask task2 = new MyDoPstAsyncTask();
task2.execute();
}
}
class MyDoGetAsyncTask extends AsyncTask<String,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... strings) {
HttpClient client = new DefaultHttpClient();
String urlString = "http://192.168.0.198:8080/MyAndroidServlet/MyServlet?username=kangsang";
HttpGet get = new HttpGet(urlString);
get.setHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
try {
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
int code = statusLine.getStatusCode();
if (code == HttpURLConnection.HTTP_OK){
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while (line!=null){
Log.d("",""+line);
line = br.readLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "返回結果";
}
}
class MyDoPstAsyncTask extends AsyncTask<String,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected String doInBackground(String... strings) {
String urlString = "http://192.168.0.198:8080/MyAndroidServlet/MyServlet?username=zhangsan";
try {
URL url = new URL(urlString);
URLConnection connect = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connect;
httpConnection.setRequestMethod("POST");
//設置連接超時時間
httpConnection.setConnectTimeout(30000);
//讀取超時時間
httpConnection.setReadTimeout(30000);
//設置編碼格式
// 設置接受的數據類型
httpConnection.setRequestProperty("Accept-Charset", "utf-8");
// 設置可以接受序列化的java對象
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//設置請求方法
httpConnection.setRequestMethod("POST");
//設置客戶端可以給服務器提交數據,默認是false的。post方法必須設置爲true
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
//post方法不允許使用緩存
httpConnection.setUseCaches(false);
String params = "username=zhangsan&password=lisi";
httpConnection.getOutputStream().write(params.getBytes());
int code = httpConnection.getResponseCode();
System.out.println("狀態碼"+code);
if(code == HttpURLConnection.HTTP_OK){
InputStream is = httpConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = br.readLine();
while(line!=null){
System.out.println(line);
line = br.readLine();
}
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
}
}