您的位置:首页 > 理论基础 > 计算机网络

android 网络通信 方案1 httpclient

2012-01-09 14:31 423 查看
apace httpclient为客户端编程提供高效、功能丰富的工具包支持。
try{

HttpClient hc=new DefaultHttpClient();

HttpGet get=new HttpGet("http://www.google.com");

HttpResponse rp=hc.execute(get);

if(rp.getStatusLine().getStatus()==HttpStatus.SC_OK)

{

........//处理数据

}

catch(IOException e){

...

}
 public class LearnActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);TextView tv=(TextView)findViewById(R.id.hello);String httpurl="www.baidu.com";//实例化http请求,httppostHttpPost httprequest=new HttpPost(httpurl);//用NameValuePair 来保存要传递的post参数List<NameValuePair> params=new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("par","HttpClient"));try{//设置字符串HttpEntity httpentity =new UrlEncodedFormEntity(params,"gb2312");//设置请求httpresquest的编码httprequest.setEntity(httpentity);//取得默认的httpclientHttpClient httpclient=new DefaultHttpClient();//执行http连接HttpResponse httpresponse=httpclient.execute(httprequest);if(httpresponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){String strresult=EntityUtils.toString(httpresponse.getEntity());tv.setText(strresult);}else{tv.setText("come on ,baby!");}}catch(ClientProtocolException e){tv.setText(e.getMessage().toString());}catch (IOException e) {tv.setText(e.getMessage().toString());}catch (Exception e) {tv.setText(e.getMessage().toString());}}}
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);TextView tv = (TextView) findViewById(R.id.hello);//url地址String httpurl = "www.baidu.com";//实例化http请求类型: httpgetHttpGet httpRequest=new HttpGet(httpurl);try{//实例化httpclient对象HttpClient httpclient=new DefaultHttpClient();//通过Httpclient执行请求HttpResponse httpResponse=httpclient.execute(httpRequest);//判断请求成功与否if(httpResponse.getStatusLine().getStatusCode()== HttpStatus.SC_OK){String strResult=EntityUtils.toString(httpResponse.getEntity());tv.setText(strResult);}else{tv.setText("come on ,girls");}}catch(ClientProtocolException e){tv.setText(e.getMessage().toString());}catch (IOException e) {tv.setText(e.getMessage().toString());}catch (Exception e) {tv.setText(e.getMessage().toString());}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: