I have a web service in PHP which returns a String, he recives two parametres, id and te.
I've tested its using with the mozzila addon poster, so i decided to use it for my android app.
This is my android code:
final String query = null;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("id", num);
rp.put("te", tab);
Log.i("http","before send\n");
client.post("http://appdomain.hol.es/webService.php",rp, new JsonHttpResponseHandler(){
public void onSuccess(String jObject)
{
query.replace(query, jObject);
Log.i("http","recived: "+jObject+"\n");
}
public void onFailure(Throwable arg0)
{
Log.i("http","fail");
}
});
I'm debugging whith log.i and i've could seen that it doesn't show neither recived neither fail.
can anyone helpl me?
PD: i leave the most relevant of webService
$id = $_POST["id"];
$te = $_POST["te"];
$query = "SELECT `preg` , `respA` , `respB` , `respC` , `respD` , `respV`FROM `".$te."` WHERE `id` =".$id;
$resultado= mysql_query($query,$link);
$arraySalida = array();
while($registro = mysql_fetch_assoc ($resultado) ):
$cadena = "{$registro['preg']};{$registro['respA']};{$registro['respB']};{$registro['respC']};{$registro['respD']};{$registro['respV']}";
$arraySalida[]= $cadena;
endwhile;
echo implode(":",$arraySalida);
the solution of @jaimin works but the compiler says: Type mismatch: cannot convert from AsyncTask to String in (!)
this is the code:
public String BBDD(int num, String tab)
{
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(String.valueOf(num),tab);
/*(!)*/String resul = httpAsyncTask.execute("http://opofire.hol.es/webServiceOpoFire.php");
return resul;
}
for Http Post i'll suggest you to use AsyncTask<> which will run in separate thread from UI
here is the code i am using since two months and its working fine
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private String id,te;
public HttpAsyncTask(String id,String te){
this.id = id;
this.te = te;
}
@Override
protected String doInBackground(String... urls) {
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
// pass parameters in this way
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "value "));
nameValuePairs.add(new BasicNameValuePair("te", "value"));
//add data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
// TODO Auto-generated method stub
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
for passing values you can create constructor like this.
form your activity do this
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(id,te);//this will pass variables values
String ResultfromServer = httpAsyncTask.execute(urlStr);// String ResultfromServer is your response string
and in AsyncTask I've created constructor
this is very helpful for me hope it will help you too
Look at below code for posting data to php
class PlaceOrder extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPst = new HttpPost(
"http://appdomain.hol.es/webService.php");
ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(
2);
// add ur parameter here
parameters.add(new BasicNameValuePair("id", value1);
parameters.add(new BasicNameValuePair("te", value2);
httpPst.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse httpRes = httpClient.execute(httpPst);
String str=convertStreamToString(httpRes.getEntity().getContent()).toString();
Log.i("mlog","outfromurl"+str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}