I recommend you use the OkHttp library for networking. Your example might be something like this
private final OkHttpClient client = new OkHttpClient();
public String sendData(double latitude, double longitude){
try {
RequestBody formBody = new FormBody.Builder()
.add("Latitude", Double.toString(latitude))
.add("Longitude", Double.toString(longitude))
.build();
Request request = new Request.Builder()
.url("http://httpbin.org/post")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
return "Error: " + e.getMessage();
}
}
Remember to run the network code in AsyncTask
class IOAsyncTask extends AsyncTask<Location, Void, String> {
@Override
protected String doInBackground(Location... params) {
return sendData(params[0].getLatitude(), params[0].getLongitude());
}
@Override
protected void onPostExecute(String response) {
Log.d("networking", response);
}
}
And this may be the method of onCreate
your activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Location current = new Location("");
current.setLatitude(23.9569596);
current.setLongitude(12.567567);
new IOAsyncTask().execute(current);
}
Note that I use http://httpbin.org/post
as a remote address, you must replace its endpoint URL. In my case, the answer is:
{
"args": {},
"data": "",
"files": {},
"form": {
"Latitude": "23.9569596",
"Longitude": "12.567567"
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "39",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "okhttp/3.0.1"
},
"json": null,
"origin": "xxx.xx.xxx.xx",
"url": "http://httpbin.org/post"
}