Can't issue http requests from Android to Django webserver with Apache - java

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.

Related

Java HttpClient error

When I try to send a POST request with an HttpClient to a website which uses CloudFlare, I don't get the website page content.
It looks like I get "blocked" from CloudFlare.
How can I get a solution?
This is the code I use:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://website/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "Bob"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
/*
* Execute the HTTP Request
*/
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
String content = EntityUtils.toString(respEntity);
}
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
First check and make sure you are sending required parameters in your request and try adding user agent in your request :
params.add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0");
If you really want to check which parameters are being sent in request when you are doing it from browser, one way I know is to use Firefox extension Tamper Data. It will show you all parameters of header and post data and will allow you to modify them also.
check your server not blocked post requests in (CORS) by default

How to connect Android app with MySQL database through PHP

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
}

how to send cURL in Android to REST service

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");

Android http post advanced request with body on hostmachine

I would like to do a HTTP post request from my virtual android device on the hostmachine.
Below you'll see an image on how I post, by using the old WebFetch tool.
I don't know what URL to use for calling the hostmachine?
I got no idea how my body string can be used an input?
Does anybody have an idea on how to solve this?
If you want to connect to the computer which is running the Android simulator, use the IP address 10.0.2.2. You can read more about it here.
Also check out the accepted answer in following question to see how json can be send as post data:
How to send POST request in JSON using HTTPClient?
you can use following code to make HTTP get request:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://10.0.2.2:port/your_path_with_parameter";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}

Using PHP sessions with my android application to login

I am trying to make a login script for my android application, the script will send my email and password to the PHP server, verify the login and then create a PHP session so that the user stays logged in. This is my code,
HttpPost httppost = new HttpPost("http://server.com/login.php");
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
public String login() {
String userID = "";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "e#e.com"));
nameValuePairs.add(new BasicNameValuePair("password", "admin"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
userID = EntityUtils.toString(response.getEntity());
//Log.v("Login response", "" + userID);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return userID;
}
This script successfully sends data to my server and my PHP successfully logs the user on. I have placed "HttpClient httpclient = new DefaultHttpClient();" outside my main login method. This has helped store the session until I call upon another class, then it just resets the session again. So I am wondering how I can alter the code so that "httpclient" is somehow stored so I can keep the session and stay logged into my server. Thank you!
Android Http get Session Cookie
Get the cookie session ID and use that cookie in the next requests to the server.
Another way is to make your php code echo a string containing the session_id in its response to login.Let the android app retrieve this id and store it. Any future requests can be made by using post method with sess_id=stored id
<?php
if(isset($_POST['sess_id']))
{
session_id($_POST['sess_id']); //starts session with given session id
session_start();
$_SESSION['count']++;
}
else {
session_start(); //starts a new session
$_SESSION['count']=0;
}
echo session_id();
?>

Categories