HttpClient
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;
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.