android通過httpPost向伺服器傳送請求 .
import java.util.List;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.util.Log;
public class RequestByHttpPost {
public static String TIME_OUT = "操作超時";
public static String doPost(List<NameValuePair> params,String url) throws Exception{
String result = null;
// 新建HttpPost物件
HttpPost httpPost = new HttpPost(url);
// 設定字符集
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 設定引數實體
httpPost.setEntity(entity);
// 獲取HttpClient物件
HttpClient httpClient = new DefaultHttpClient();
//連線超時
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
//請求超時
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
try {
// 獲取HttpResponse例項
HttpResponse httpResp = httpClient.execute(httpPost);
// 判斷是夠請求成功
if (httpResp.getStatusLine().getStatusCode() == 200) {
// 獲取返回的資料
result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i("HttpPost", "HttpPost方式請求成功,返回資料如下:");
Log.i("result", result);
} else {
Log.i("HttpPost", "HttpPost方式請求失敗");
}
} catch (ConnectTimeoutException e){
result = TIME_OUT;
}
return result;
}
}