android 向web服务器发送post请求并获取结果,因为 需要访问到网络必须要有权限,先在AndroidManifest.xml中加入如下配置:
发送post请求并获取结果的activity 代码如下:
<uses-permission android:name="android.permission.INTERNET" />
发送post请求并获取结果的activity 代码如下:
package httppost.pack;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class AndroidHttpPost extends Activity {
/** Called when the activity is first created. */
String action="http://www.beijibear.com/android_post.php";
HttpPost httpRequest=null;
List <NameValuePair> params=null;
HttpResponse httpResponse;
TextView tv=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv=(TextView)findViewById(R.id.textView1);
/*建立HttpPost连接*/
httpRequest=new HttpPost(action);
/*Post运作传送变数必须用NameValuePair[]阵列储存*/
params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username","beijibear"));
try {
//发出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//取得HTTP response
httpResponse=new DefaultHttpClient().execute(httpRequest);
//若状态码为200
if(httpResponse.getStatusLine().getStatusCode()==200) {
//取出回应字串
String strResult=EntityUtils.toString(httpResponse.getEntity());
tv.setText(strResult);
}else{
tv.setText("Error Response"+httpResponse.getStatusLine().toString());
}
} catch (Exception e) {
// TODO Auto-generated catch block
tv.setText(e.getMessage().toString());
}
}
}