package com.example.postdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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 android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpPost post=new HttpPost("http://www.baidu.com");//创建post对象 并传入URL参数 注意post类型的Url不带参数
HttpClient httpclient=new DefaultHttpClient();//创建httpclient对象 并实例化
List<BasicNameValuePair> pairs=new ArrayList<BasicNameValuePair>();//设置BasicNameValuePair类型的ArrayList集合 用来存储URL参数
pairs.add(new BasicNameValuePair("a", "30"));//往集合里添加元素
pairs.add(new BasicNameValuePair("b", "15"));
try {
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs);//UrlEncodedFormEntity实现了HttpEntity接口
post.setEntity(entity);
HttpResponse hr=httpclient.execute(post);//之后和get方法一样
BufferedReader br=new BufferedReader(new InputStreamReader(hr.getEntity().getContent()));
String line=null;
String content=null;
while((line=br.readLine())!=null)
{
content+=line;
}
System.out.println(content);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
post和get的区别
get的Url参数可以在httpget构造方法中直接传参 显示可见
而post的Url参数是不能在httppost构造方法中直接传参的 而且隐藏不可见 所以 需要引入List<BasicNameValuePair>集合 并进行传参
同时多了UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs);//UrlEncodedFormEntity实现了HttpEntity接口
post.setEntity(entity);这两步 其余的和get请求类似