发送GET请求

时间:2016-04-11 18:50:31

标签: php android get

我知道有很多这样的主题,我疯狂搜索并阅读了大部分内容,但无法找到真正有帮助我的工作的答案。

我想要做的很简单,我只想使用GET发送2个值并将它们保存在MySql中。

我已经创建了PHP文件并且正在运行(我在chrome中手动测试),我在Android Studio中有这个代码:

try {
        URL url = new URL("http://myWebsite.com/connection.php");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("value1","blabla");
        urlConnection.setRequestProperty("value2","blabla");

    } catch(Exception e){
    Log.d("Exception",e.toString());
    }

我不知道还有什么可以尝试,这样的事情应该很简单,但我不能找到解决方案。

谢谢!

编辑: 我也尝试过:

try {
        URL url = new URL("http://myWebsite.com/connection.php?value1=blabla&value2=blubla");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

    } catch(Exception e){
    Log.d("Exception",e.toString());
    }

编辑2: 将其添加到我的代码中:

private class MyTask extends AsyncTask<Void, Void, Void> {


        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL url = new URL("http://mySite.tk/connection.php?value1=blabla&value2=blubla");
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                Log.d("Progress","Sending..");
                urlConnection.connect();
                Log.d("Progress","Sent!");

            } catch(Exception e){
                Log.d("Message",e.toString());
            }
            return null;
        }
    }

现在我打电话给#34; new MyTask()。execute()&#34;单击按钮时,但不起作用:(

2 个答案:

答案 0 :(得分:1)

获取值不会作为属性发送。它们是作为URL的一部分发送的。 http://example.com/myurl?variable1=value1&variable2=value2

答案 1 :(得分:1)

您可以轻松地通过名为Volley的Google图书馆发送GET请求,它是专为Android上的请求而设计的

我建议您考虑使用Volley来满足您的未来需求,以下是GET请求的示例:

final String url = "http://yourScript.com/scipt.php";

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
    new Response.Listener<JSONObject>() 
    {
        @Override
        public void onResponse(JSONObject response) {   
                        // display response     
            Log.d("Response", response.toString());
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {            
            Log.d("Error.Response", response);
       }
    }
){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> map = new HashMap<>();
            map.put("parameter1", param1);
            map.put("parameter2", param2); 

            return map;
        }
    };

// add it to the RequestQueue   
queue.add(getRequest);
相关问题