在Android中发出HTTP请求的最常用/最常用的方式

时间:2015-09-11 05:19:53

标签: php android mysql httprequest

嘿,我是Android新手,正在研究一个基本的Android应用程序,它试图通过PHP脚本连接到MYSQL数据库。所以,我需要通过发出HTTP请求来访问这个PHP。我跟随的教程建议在java中创建一个JSON Parser类,它使用不推荐使用的DefaultHTTPClient和Asynctask。显然有一些叫做httpurlconnection的东西,我觉得和httpclient一样。还有Volley图书馆显然“更快”。

我想知道,我的方案的推荐做法是什么?现在我只是在登录/注册应用程序的一部分。

2 个答案:

答案 0 :(得分:1)

有太多第三方库可供网络运营:

以下是一些建议:

    Google的
  1. Volley
  2. Retrofit by squre
  3. Here也是这两个库的性能比较。 根据您的要求选择一个。

    希望它会有所帮助。!!

答案 1 :(得分:0)

在您的应用程序的主要活动中,请填写以下内容。

您需要在另一个无法在主线程上运行它们的线程上运行网络请求。使用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

    }