I have been trying to get my Android App to post data to a PHP file, which then writes that data to a database, however I'm having a bit of trouble with it.
I'm getting this error, however it's not force closing or anything.
Logcat Output:
08-13 20:29:42.859: I/postData(11950): HTTP/1.1 200 OK
08-13 20:29:42.859: E/log_tag(11950): Error in http connectionjava.lang.IllegalStateException: Content has been consumed
Here is the code in question that's doing all my HTTP POST stuff, the android side of things:
SubmitWord task = new SubmitWord();
task.execute(new String[] { "http://www.hanged.comli.com/main.php" });
The above code calls this asynchronous task:
private class SubmitWord extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",myId));
nameValuePairs.add(new BasicNameValuePair("rival",newname));
nameValuePairs.add(new BasicNameValuePair("word","HELLOHOMO"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
InputStream is = entity.getContent();
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result)
{
mText.setText("DONE");
}
}
Here is the PHP side of things:
<?php
/// REMOVED DATABASE DETAILS
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
mysql_query("INSERT INTO currentgames (victim, rival, wordguess, won) VALUES('$victim', '$rival', '$word', '$won'))");
I'm fairly sure it's just the Java/Android part that I've gotten wrong, but I can't figure out for the life of me what I'm doing wrong, I have tried various different methods of POSTING data and read a number of tutorials on using HTTPOST. Maybe I'm just not understanding correctly.
The culprit is you are calling getContent(); twice.
As per javadoc
Returns a content stream of the entity. Repeatable entities are expected to create a new instance of InputStream for each invocation of this method and therefore can be consumed multiple times. Entities that are not repeatable are expected to return the same InputStream instance and therefore may not be consumed more than once.
Related
I am trying to create a simple post request to a web API and parse the response received. After quite a lot of search, I was able to come up with the following code:
public class access {
public static void main(String[] args) {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://xxxxx/RSAM_API/api/Logon");
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Request parameters and other properties.
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(2);
urlParameters.add(new BasicNameValuePair("UserId", "xxxxxx"));
urlParameters.add(new BasicNameValuePair("Password", "xxxxxxx"));
try {
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while(null !=(line=rd.readLine())){
System.out.println(line);
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
In the above code, I am doing an post request to the URL login endpoint. the response I see after parsing it is:
An error occurred, please try again or contact the administrator with this error id, 26225
I am able to login to the URL through the browser manually. Not sure where I am going wrong in the code.
Is my approach correct in the first place? Can I be sure that my code is right? If it is, why is the response an error?
Any help would be appreciated. Thank you.
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 want to know why does this code not execute? I'm trying to send my data from my device via POST method but there is no error. The app just finishes by itself on my device by communicating "My app was stopped.:
Here is execution:
KlientNameValue kn = new KlientNameValue(getApplicationContext());
kn.new MyAsyncTask().execute(zam.klient.getNazwa(),zam.klient.getNip(),zam.klient.getAdres());
And here is code:
public class KlientNameValue {
List<NameValuePair> KlientNameValuePairs = new ArrayList<NameValuePair>();
Context context;
public KlientNameValue(Context context) {
super();
this.context=context;
}
public class MyAsyncTask extends AsyncTask<String, Void, Void> {
#Override protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0], params[1], params[2]);
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(context , "Zlecenie zostało wysłane",
Toast.LENGTH_LONG).show();
}
void postData(String nazwa, String nip, String adres) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("here is my default link :)");
try { // Add your data
KlientNameValuePairs = new ArrayList<NameValuePair>();
KlientNameValuePairs.add(new BasicNameValuePair("Kli_imie", nazwa));
KlientNameValuePairs.add(new BasicNameValuePair("Kli_adres", adres));
KlientNameValuePairs.add(new BasicNameValuePair( "Kli_nr_telefonu",
nip));
httppost.setEntity(new UrlEncodedFormEntity( KlientNameValuePairs));
HttpResponse response = httpclient.execute(httppost);
//httppost.setEntity(new UrlEncodedFormEntity(
// ZamowienieNameValuePairs)); // HttpResponse response1 =
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace(); }
}
}
}
Error:
02-15 17:45:24.695: E/AndroidRuntime(21890): at android.widget.Toast.<init>(Toast.java:94)
02-15 17:47:19.343: W/SingleClientConnManager(22288): Invalid use of SingleClientConnManager: connection still allocated.
02-15 17:47:19.343: W/SingleClientConnManager(22288): Make sure to release the connection before allocating another one.
Invalid use of SingleClientConnManager: connection still allocated.
You are executing the http request two times that is completely wrong before you consume it. So remove the second httpclient.execute(httppost); because you have already execute this http request.
and call this
httpResponse.getEntity().consumeContent();
Above method is called to indicate that the content of this entity is no longer required. All entity implementations are expected to release all allocated resources as a result of this method invocation
public static DefaultHttpClient getThreadSafeClient() {
DefaultHttpClient client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(
new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
use this code so that your exception of free resource and allocate or being used will not come
This exception can happen when two or more threads interact with a single org.apache.http.impl.client.DefaultHttpClient
or simply give new object to each request when and where ever you are calling you get or post http client request to interact with server to fetch the data or download the large file
like
String post_url="http://www.google.com";
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpost = new HttpPost(Post_url);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = client.execute(httpost);
String response= EntityUtils.toString(httpResponse.getEntity());
as you like in code to retrieve the response
I want to make a request to a page that contains a .csv file, get it back and parse it. I've been searching a lot and I found a lot of questions about accessing secure connections and stuff, but I think my problem is different. Below is my code:
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("https://recursos-data.buenosaires.gob.ar/bicicletas-publicas/estaciones-bicis.csv");
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
Log.v("response code", response.getStatusLine()
.getStatusCode() + "");
HttpEntity entity = response.getEntity();
When I debug it and get to the line HttpResponse response = httpClient... the program doesn't throw any exception but it doesn't keep on going either. It just hangs there. I don't know what the problem is. I've used this code before.
I'm using Android 2.2. Any ideas?
I want to call specific php function on server from Android application and also to send some parameters. Till now I achieved that I can open php file using HttpClient and executed data transfer to Json and show that in my app. So, now I want to be able to call specific function and send parameter to it, how can I do that??
Thanks.
Here is a piece of code I wrote for registering a new username using JSON:
public static boolean register(Context myContext, String name, String pwd) {
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
List<NameValuePair> nameValuePairs;
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"http://X.X.X.X/register.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e) {
Toast.makeText(myContext, "error" + e.toString(), Toast.LENGTH_LONG)
.show();
return false;
}
if (buffer.charAt(0) == 'Y') {
return true;
} else {
return false;
}
}
If you notice:
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("User", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pwd.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
in that piece you can send parameters.
The method simply sends User and Password to the register.php.
If the User is already taken, 'N' is returned; otherwise creates the User and returns 'Y'.
On the server side, you treat them as POST information, so:
$user = $_POST['User'];
It should do for your case :)
Cheers!
Present or wrap-up those specific php functions with in a web-service together with your required parameters and call that web-service including the input parameters from your android to get things done.
You need to use WebServices for this work.
http://www.php.net/manual/en/book.soap.php