import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTask<String, String, String>() {
@Override
protected String doInBackground(String... params) {
String result = getData();
return result;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(MainActivity.this, result, 0).show();
super.onPostExecute(result);
}
}.execute();
}
//httpclient 是用HttpUrlConnction封装的一套api
protected String getData() {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
// HttpGet get = new HttpGet("http://www.baidu.com");
//Post请求
HttpPost post = new HttpPost("http://www.baidu.com");
List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", "zhangsan"));
list.add(new BasicNameValuePair("pass", "1234"));
HttpEntity entity = new UrlEncodedFormEntity(null, "utf-8");
//post对象是 指定了要访问的路径 然后给这个路径的对象 设置了一个entity
//entity中包含了所有的请求数据
//所以可以把数据发送给指定的路径
post.setEntity(entity);
HttpResponse execute = client.execute(post);
int code = execute.getStatusLine().getStatusCode();
if(code == 200){
result = EntityUtils.toString(execute.getEntity());
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}