-2

I'm having the hardest time, what I want is for my android application to send a STRING to my server, my server will then choose a function based upon what STRING was sent in PHP. Once the function is done, it will return a JSONObject. I don't want to use any Deprecated methods. I'm trying to implement the sending a STRING to the server to parse and use an appropriate function in PHP then send a JSON back to my android application. Can anyone please show some code from the android side?

So what I'm looking for is, help with the Android code to send a STRING to the server, then read the response from the server which will be a JSON.

Steven R
  • 323
  • 2
  • 6
  • 18
  • post code where you are unable to work out . confused where is the issue android OR php? – KOTIOS Sep 18 '15 at 04:35
  • As it stands your question is at the risk of getting close votes. Explain better. Try to split the php and android issues if you can – e4c5 Sep 18 '15 at 04:36
  • I think i'm more confused in the Android and how to properly send the STRING that i want to send to PHP. Im guessing the PHP code would be just `if(_POST=$method)` right? – Steven R Sep 18 '15 at 04:37
  • Okay, hopefully i fixed any confusion – Steven R Sep 18 '15 at 04:49

1 Answers1

1

For Android you can use HTTP Connection URL. An example is mentioned here How to add parameters to HttpURLConnection using POST

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "Chatura"));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

..

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

For PHP just accept a post request which is coming form Andrid as below

<?php
echo '{ "name" = "Hello ' . htmlspecialchars($_POST["name"]) . '"}';
?>
Community
  • 1
  • 1
Chatura Dilan
  • 1,502
  • 1
  • 16
  • 29