I'm trying to create a basic application where I want to send a request from android to php server like this: http://www.eg.com/eg.php?a=blabla:blablabla:bla.
Then when i get this data I want do something like this:
if(isset($_GET['a'])) {
$a = $_GET['a'];
$array = explode(':', $a);
$data1 = $array[0];
if($data1 == "blabla") {
Send response to android here..
}
}
The problem is that i dont know how to send data to and back from android to php server. I looked at many answers but most send json data or use the depreciated apache http library or does not talk anything about the php server side or are specific to secnario of that person. Please can you give me a very clear answer on how to do this, thanks :)
If there is an answer that already covers this question, please provide my with the url for that answer before voting me down.
I have finally found a simple solution with the help of the comments and hours of research:
You can simple call this method by using this:
HashMap<String , String> postDataParams = new HashMap<String, String>();
postDataParams.put("name", "value");
performPostCall("URL", postDataParams);
Java code:
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
Log.e("Res:", response);
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
On the php side you can get the data by using:
$_POST['name']
you can send back response by simply doing this:
echo "response here..";