【问题标题】:Most Standard/Common Way to Make HTTP Requests in Android在 Android 中发出 HTTP 请求的最标准/常见方式
【发布时间】:2015-09-11 05:19:52
【问题描述】:

嘿,我是 Android 新手,正在开发一个基本的 Android 应用程序,它试图通过 PHP 脚本连接到 MYSQL 数据库。所以,我需要通过发出 HTTP 请求来访问这个 PHP。我所遵循的教程建议在 java 中创建一个 JSON Parser 类,该类使用已弃用的 DefaultHTTPClient 和 Asynctask。显然有一个叫做 httpurlconnection 的东西,我认为它和 httpclient 做同样的事情。还有显然“更快”的 Volley 库。

我想知道,我的场景推荐的做法是什么?现在我正在处理应用程序的登录/注册部分。

【问题讨论】:

  • AsyncTask 中使用HttpURLConnection

标签: php android mysql httprequest


【解决方案1】:

可用于网络操作的第三方库太多:

这里有一些建议:

  1. Volley 来自 Google
  2. Retrofit by squre

Here 也是这两个库的性能比较。 根据您的要求选择一个。

希望它会有所帮助。!!

【讨论】:

    【解决方案2】:

    在应用程序的主要活动中放置以下内容。

    您需要在另一个线程上运行网络请求,而不能在主线程上运行它们。使用 HttpURLConnection 与服务器和我编写的其余代码建立连接。从服务器收到响应后,处理程序可用于在主线程上显示响应。

     Handler mHandle = new Handler(){
            @Override
            public  void handleMessage(Message msg)
            {
                String data = (String) msg.obj;
                Toast.makeText(getApplicationContext(),data,Toast.LENGTH_SHORT).show(); //show the response recieved from the server
            }
        };
    
        Handler mHandle2 = new Handler(){
            @Override
            public  void handleMessage(Message msg)
            {
                String data = (String) msg.obj;
                Toast.makeText(getApplicationContext(),"This is a handler2 here so please ignore this test here to test the functionality",Toast.LENGTH_SHORT).show();
            }
        };
    
     public void send(View v)
        {
    
            final ContentValues  values = new ContentValues();
            values.put("data1", "Stackoverflow answer :)");
    
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try{
                        final URL url = new URL("http://example.com/resp.php");
                        HttpURLConnection con = (HttpURLConnection) url.openConnection();
                        con.setDoOutput(true);
                        con.setDoInput(true);
                        con.setRequestMethod("POST");
                        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        String parameters = "data1=" + URLEncoder.encode("SOMETHING", "UTF-8");
                        con.setRequestProperty("Content-Length", "" +
                                Integer.toString(parameters.getBytes().length));
                        con.setRequestProperty("Content-Language", "en-US");
                        con.setUseCaches(false);
                        con.setRequestProperty("Charset", "UTF-8");
                        OutputStream OS = con.getOutputStream() ;
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
                        writer.write(parameters);
                        writer.flush();
                        writer.close();
                        int statuscode = con.getResponseCode();
                        BufferedInputStream bufstream = new BufferedInputStream(con.getInputStream());
                        byte[] somedata = new byte[1024];
                        int byteRead = 0;
                        String datahere = "",temp= "";
                        while(  (byteRead = bufstream.read(somedata)) != -1 )
                        {
                             /* read(byte[] buffer, int byteOffset, int byteCount)
                            Reads up to byteCount bytes from this stream and stores them in the byte array buffer starting at byteOffset. */
                            temp = new String(somedata,0,byteRead);
                            datahere = datahere+temp;
                            // Toast.makeText(getApplicationContext(),datahere,Toast.LENGTH_SHORT).show();
                        }
                        Message msg=new Message();
                        Message msg2=new Message();
                        msg.obj=datahere;
                        mHandle.sendMessage(msg);
                        msg2.obj="This is just a test";
                        mHandle2.sendMessage(msg2);
                    }  catch (MalformedURLException e) {
                        Toast.makeText(getApplicationContext(),"Error1",Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    } catch (ProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        Log.e("ReleaseInfo", "JSoup get didnt get a document", e);
                    }
    
                }
            };
            new Thread(runnable).start(); //Network request do not run on the main thread so run it on another thread
    
        }
    

    【讨论】:

      【解决方案3】:

      我为您提供一个解决方案

      我编写了一个项目 (EocboxVolleyBox) 来展示如何使用 GsonVolley 从 Internet 获取 JSON 并将其保存在 Java 对象中>OkHttp

      EocboxVolleyBox是一个集成Android Volley库、OkHttp和Gson的工具箱。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-01
        • 2013-06-01
        • 1970-01-01
        • 2011-12-19
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多