首页 >php教程 >php手册 >Android 4.0调用http接口php网站的api

Android 4.0调用http接口php网站的api

WBOY
WBOY原创
2016-06-06 19:59:541746浏览

(本人菜鸟刚学)看网上教程写了一个很简单的HttpGet测试一下,结果出了一堆的报错! 代码: public static String getApi(String url){ String cont = null; HttpGet httpGet = new HttpGet(url); DefaultHttpClient httpClient = new DefaultHttpClient();

      (本人菜鸟刚学)看网上教程写了一个很简单的 HttpGet测试一下,结果出了一堆的报错!


代码:


<span> public static String getApi(String url){

               String cont = null;
               HttpGet httpGet = new HttpGet(url);                     
               DefaultHttpClient httpClient = new DefaultHttpClient(); 
               try {
                   HttpResponse httpResponse = httpClient.execute(httpGet); 
                   int reCode = httpResponse.getStatusLine().getStatusCode();
                   if (reCode == HttpStatus.SC_OK) {
                       cont = EntityUtils.toString(httpResponse.getEntity());
                       return cont;
                   }
               } catch (ClientProtocolException e) {
                   e.printStackTrace();
               } catch (IOException e) {
                   e.printStackTrace();
               }
               return "";

    }</span>


 报线程问题,看网上资料说从2.3以后就必须在线程里面运行,然后网上各种写法,看到头大坑爹的而且写进来还不行,接着报错...然后...擦还是不行....还是自己写一下.....希望可以帮助到新手

在onCreate里面先初始化

 handler=new Handler();  //当然最上面还要定义private Handler handler;

然后在你的触发事件里面写


public void login_submit(View v){
        new Thread(){
            @Override
            public void run() {
                String url = "http://192.168.1.188/123.html";
                 rs = HttpApi.getApi(url);
                
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(login.this,rs,Toast.LENGTH_SHORT).show();
                    }
                });
            }}.start();
    }


好这样就差不多了。最后还要在

AndroidManifest.xml 里面加入一句 允许联网的权限


OK搞定。。。。

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn