2

I am still a little skeptical as to how to connect my Android app to a PHP script. I saw somewhere that the following code will connect the app to the server. But I am new at android so I do not know how to really use it.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://url.to.my.app.com");
HttpResponse response = httpClient.execute(httpGet);
// handle response'

I understand that this opens a connection to an online server, but what I do not understand is what kind of response is returned by the server and how to process it. Also, I want to know how to send data through POST to the server from my app.

(If you could provide some code of your own, that would be helpful too) Thanks!

5
  • 1
    You could implement a RESTful API service: stackoverflow.com/questions/3197335/restful-api-service Commented May 17, 2013 at 7:37
  • Read this tutorial Commented May 17, 2013 at 7:40
  • I require to connect to the PHP script with a DefaultHttpClient ONLY. I want to learn how to use it. Commented May 17, 2013 at 7:42
  • RESTFUL web service would be the best option Commented May 17, 2013 at 7:43
  • This link will give you a clear idea android,Php,MySql Commented May 17, 2013 at 7:49

1 Answer 1

1

This will open a connection and send a http GET request to server. Your PHP script executes on the server side for this request and returns some contents. You can use folowing code to process the response.

HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();

    String result = RestClient.convertStreamToString(instream);        
}

For POST execution you need to do something like this.

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
    // Add your data
    List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    nvps.add(new BasicNameValuePair("test1","test1" ));
    nvps.add(new BasicNameValuePair("test2", "test2" ));
    httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.