Eclipse利用HttpClient 寫post和get連線到後臺
檔案目錄如下:
第一個包程式碼如下:
package cn.itcast.login;
import cn.itcast.login.service.DataService;
import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts.Data;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DemoActivity extends Activity implements OnClickListener {
private EditText mEtName;
private EditText mEtPassword;
private EditText mEtFilePath;
private Button mBtLogin;
private Button mBtLoginPost;
private Button mBtLoginClientGet;
private Button mBtLoginClientPost;
private Button mBtLoginClientPostFile;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mEtName = (EditText) this.findViewById(R.id.et_name);
mEtPassword = (EditText) this.findViewById(R.id.et_password);
mBtLogin = (Button) this.findViewById(R.id.bt_login);
mBtLoginPost = (Button)this.findViewById(R.id.bt_login_post);
mBtLoginClientGet = (Button)this.findViewById(R.id.bt_login_client_get);
mBtLoginClientPostFile = (Button)this.findViewById(R.id.bt_login_client_post_file);
mBtLoginClientPost = (Button)this.findViewById(R.id.bt_login_client_post);
mEtFilePath = (EditText)this.findViewById(R.id.et_file_path);
mBtLogin.setOnClickListener(this);
mBtLoginPost.setOnClickListener(this);
mBtLoginClientGet.setOnClickListener(this);
mBtLoginClientPost.setOnClickListener(this);
mBtLoginClientPostFile.setOnClickListener(this);
}
@Override
public void onClick(View v) {
String name = mEtName.getText().toString().trim();
String password = mEtPassword.getText().toString().trim();
if("".equals(name)||"".equals(password)){
Toast.makeText(this, "使用者名稱或密碼不能為空", 0).show();
return;
}
String path = getResources().getString(R.string.servleturl);
switch (v.getId()) {
case R.id.bt_login:
// 通過get請求 傳送資料到伺服器
try {
String result = DataService.sendDataByGet(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "訪問網路異常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_post:
try {
String result = DataService.sendDataByPost(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "訪問網路異常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_client_get:
try {
String result = DataService.sendDataByHttpClientGet(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "訪問網路異常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_client_post:
try {
String result = DataService.sendDataByHttpClientPost(path, name, password);
Toast.makeText(this, result, 0).show();
} catch (Exception e) {
Toast.makeText(this, "訪問網路異常", 0).show();
e.printStackTrace();
}
break;
case R.id.bt_login_client_post_file:
try {
String filepath = mEtFilePath.getText().toString().trim();
if("".equals(filepath)){
Toast.makeText(this, "路徑不能為空", 0).show();
return ;
}
String result = DataService.sendDataByHttpClientPost(path, name, password, filepath);
Toast.makeText(this, result, 0).show();
System.out.println(new String( result.getBytes("iso8859-1"),"utf-8"));
} catch (Exception e) {
Toast.makeText(this, "訪問網路異常", 0).show();
e.printStackTrace();
}
break;
}
}
}
第二個包程式碼如下:
package cn.itcast.login.service;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import cn.itcast.login.util.StreamTool;
public class DataService {
/**
* 通過get請求提交資料到伺服器
*
* @param path
* 伺服器servlet的地址
* @param name
* 使用者名稱
* @param password
* 密碼
* @return 伺服器返回回來的string資料
*/
public static String sendDataByGet(String path, String name, String password)
throws Exception {
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
// 資料並沒有傳送給伺服器
// 獲取伺服器返回的流資訊
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
return new String(result);
}
// get post
// get 一次提交的資料資料量比較小 4K 內部其實通過組拼url的方式
// post 可以提交比較大的資料 form表單的形式 流的方式寫到伺服器
/**
* 採用post的方式 提交資料到伺服器
*
* @param path
* 伺服器servlet的地址
* @param name
* 使用者名稱
* @param password
* 密碼
* @return 伺服器返回的資料資訊
* @throws Exception
*/
public static String sendDataByPost(String path, String name,
String password) throws Exception {
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = "name=" + param1 + "&password=" + param2;
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
// 設定 http協議可以向伺服器寫資料
conn.setDoOutput(true);
// 設定http協議的訊息頭
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length() + "");
// 把我們準備好的data資料寫給伺服器
OutputStream os = conn.getOutputStream();
os.write(data.getBytes());
// httpurlconnection 底層實現 outputstream 是一個緩衝輸出流
// 只要我們獲取任何一個伺服器返回的資訊 , 資料就會被提交給伺服器 , 得到伺服器返回的流資訊
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
byte[] result = StreamTool.getBytes(is);
return new String(result);
} else {
throw new IllegalStateException("伺服器狀態異常");
}
}
/**
* httpclient 瀏覽器的簡單包裝
* new HttpClient 就相當於得到了一個瀏覽器
*/
public static String sendDataByHttpClientGet (String path , String name,String password) throws Exception{
//1. 獲取到一個瀏覽器的例項
HttpClient client = new DefaultHttpClient();
//2. 準備請求的地址
String param1 = URLEncoder.encode(name);
String param2 = URLEncoder.encode(password);
HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
//3. 敲回車 發請求
HttpResponse ressponse = client.execute(httpGet);
int code = ressponse.getStatusLine().getStatusCode();
if(code == 200){
InputStream is =ressponse.getEntity().getContent();
byte[] result = StreamTool.getBytes(is);
return new String(result);
}
else{
throw new IllegalStateException("伺服器狀態異常");
}
}
public static String sendDataByHttpClientPost(String path , String name,String password) throws Exception{
//1. 獲取到一個瀏覽器的例項
HttpClient client = new DefaultHttpClient();
//2. 準備要請求的 資料型別
HttpPost httppost = new HttpPost(path);
// 鍵值對
List< NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("name", name));
parameters.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
//3.設定post請求的資料實體
httppost.setEntity(entity);
//4. 傳送資料給伺服器
HttpResponse ressponse = client.execute(httppost);
int code = ressponse.getStatusLine().getStatusCode();
if(code == 200){
InputStream is =ressponse.getEntity().getContent();
byte[] result = StreamTool.getBytes(is);
return new String(result);
}
else{
throw new IllegalStateException("伺服器狀態異常");
}
}
/**
* 提交資料給伺服器 帶一個檔案
* @param path
* @param name
* @param password
* @param filepath 檔案在手機上的路徑
*
* @return
* @throws Exception
*/
public static String sendDataByHttpClientPost(String path , String name,String password ,String filepath) throws Exception{
// 例項化上傳資料的 陣列 part []
Part[] parts = {new StringPart("name", name),
new StringPart("password", password),
new FilePart("file", new File(filepath))};
PostMethod filePost = new PostMethod(path);
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
client.getHttpConnectionManager().getParams()
.setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if(status==200){
System.out.println( filePost.getResponseCharSet());
String result = new String(filePost.getResponseBodyAsString());
String ha = new String ( result.getBytes("ISO-8859-1"),"UTF-8");
System.out.println(ha);
System.out.println("--"+result);
return result;
}
else{
throw new IllegalStateException("伺服器狀態異常");
}
}
}
第三個包程式碼如下:(第三個包裡是一個工具包)
package cn.itcast.login.util;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 把一個inputstream裡面的內容轉化成一個byte[]
*/
public static byte[] getBytes(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.flush();
byte[] result = bos.toByteArray();
System.out.println(new String(result));
return result;
}
}