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!
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
}
Related
I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.
I am having trouble understanding how exactly to configure WAMP for remote (not LAN) access by an Android app to the SQL database that I have created with it.
I understand that I shouldn't be directly connecting to the database from the app but use a PHP script to query the database and return the results.
What I am not understanding is how all this fits together, Where do I put the PHP scripts, How do I access them, How do I allow and connect to the webserver to get the data out of the database.
I have followed and searched for lots of tutorials on this but they all seem to deal with only using wamp in localhost, I can successfully access the data locally but I am stumped with how to set all that up so that I could query the database from any internet connection on my android device.
Any advice on how to achieve this would be very much appreciated.
You have to upload your php script to your server :
Ex : Your php is in : myserver.com/myscript.php
In your Android app, You post your variables, and you connect your php script with HttpClient :
URL_TO_YOUR_SCRIPT = "myserver.com/myscript.php";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("userId", userId));
HttpClient httpclient = new DefaultHttpClient();
// specify the URL you want to post to
HttpPost httppost = new HttpPost(URL_TO_YOUR_SCRIPT);
try {
// create a list to store HTTP variables and their values
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
} else {
Log.e("ERROR", statusLine.getStatusCode() + "");
HttpEntity getResponseEntity = response.getEntity();
return getResponseEntity.getContent();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
In your php :
<?
$userId=$_REQUEST['userId'];
....
// in general you return a json string to get status and result
?>
I'm newbie in android, I want to get some data from my REST service, but I have some problem to initialize the method what's I send into the my REST service. you know that REST service using cURL to manipulate some data(POST,PUT,GET,DELETE). now how to send POST PUT GET DELETE method via cURL in android. do same as using httppost to send it? or how to send cURL to rest service in android?
Using HttpClient you can send POST,PUT,GET,DELETE requests. For an example POST request check here.
public void postData() {
// 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> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 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
}
}
// Newventuresmarket.com
// Steven Koelsche`
Thanks Brak.
Mars you might need to adjust headers also if needed for cURL...
try {
httppost.setHeader("Content-Type", "application/json");
httppost.setHeader("Accept", "application/json");
I need to do simple http post in my app.
Found example and created AsyncTask class. The main code doing post is this:
nameValuePairs - is post elements
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL_STRING);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
String data = new BasicResponseHandler().handleResponse(response);
How ever i get this exception
org.apache.http.client.HttpResponseException: Forbidden
What does this means ? If this something that service return, then how to see full message ?
Also if there are other way to make http post, i could try it :)
Thank you guys for help.
The exception org.apache.http.client.HttpResponseException Signals a non 2xx HTTP response as stated here : http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/HttpResponseException.html.
You can use the simple httpPOST method as below :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://Your URL/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("Name1", "Value1"));
nameValuePairs.add(new BasicNameValuePair("Name2", "Value2"));
nameValuePairs.add(new BasicNameValuePair("Name3", "Value3"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 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
}
I'm trying to issue a post request to my django webserver (which behaves correctly when accessed via browser)
my post code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://23.23.237.174/save-item");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_email", WeShouldActivity.ACCOUNT_NAME));
for (Field f : mData.keySet()) {
nameValuePairs.add(new BasicNameValuePair(f.getName(), mData.get(f)));
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Log.v("GETREFERRALSSERVICE", "backing up items");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.v("GETREFERRALSSERVICE", e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.v("GETREFERRALSSERVICE", e.getMessage());
}
my complete error in apache2/access.log (nothing shows up in error.log)
174.253.199.12 - - [16/May/2012:03:25:15 +0000] "POST /save-item HTTP/1.1" 500 53055 "-" "Apache-HttpClient/UNAVAILABLE (java 1.4)"
Does anyone have any idea what this might be/how to fix?
NOTE: this IS an error. The request is not getting through to my view, where it does with the exact same url in a browser. I'm printing out the request first thing in my view and nothing shows up in error.log
'Apache-HttpClient/UNAVAILABLE (java 1.4)' is just the Android user agent string, not an error message. Something is wrong on the server side, you should try to debug it by adding logging, etc. Does the server side require authentication? If so, you might be missing a session cookie, etc.
BTW, since it seems you are adding more than two items, there is really no point in using new ArrayList<NameValuePair>(2) just use the default constructor.
Try this:
HttpClient client = new DefaultHttpClient();
client.getParams().setBooleanParameter("http.protocol.expect-continue", false);
This solved my problem.