欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

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

程序员文章站 2022-05-17 15:36:06
...

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

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


代码:


 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 "";

    }


报线程问题,看网上资料说从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搞定。。。。