我知道有很多这样的线程,我疯狂地搜索并阅读了其中的大部分,但找不到真正对我有帮助且有效的答案。
我想做的很简单,我只想使用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;
}
}
现在我在点击按钮时调用"new MyTask().execute()",但不起作用:(
您可以使用名为Volley的谷歌库轻松发送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);