how to call php through java script in .apk - php

How to call the php through javascript in apk , i am using webwiew and html5 javascript and jquery
I want to retrieve the json data from php
function ajaxFunction() {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.addRequestInterceptor(new RequestAcceptEncoding());
httpclient.addResponseInterceptor(new ResponseContentEncoding());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.smartcloudinfo.com/game/RainbowTreasure(IPAD)/RT_IPADV1.0.40/json.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("line_value",20));
nameValuePairs.add(new BasicNameValuePair("stake_value",0.2));
nameValuePairs.add(new BasicNameValuePair("balance_value",updated_Balance));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
alert("found"+HttpResponse response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

You need to use ajax. Jquery has a built in functionality to make ajax calls. Especially if you want to post your answer in json, there is also a call in jquery to do such things.
Here is a simple sample from the jquery page:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
Or for JSON:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json) {
alert("JSON Data: " + json.users[3].name);
});

Related

Getting HTML response instead of JSON in android

I'm trying to retrieve data from mysql database located on a remote server through php into android. This worked fine while running in localhost. But when it is in remote server, I receive HTML codes instead of JSON response from server. I tried pasting the url (http://ksos.0fees.us/pgm_list.php?day=1&hall=A) in browser which resulted in correct JSON output. The HTML response is shown below.
<html><body>
<script type="text/javascript" src="/aes.js" ></script>
<script>function toNumbers(d)
{var e=[];
d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});
return e
}
function toHex()
{for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)
e+=(16>d[f]?"0":"")+d[f].toString(16);
return e.toLowerCase()
}
var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("5cb1c0309e553acda177d912f21ac485");
document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+";
expires=Thu, 31-Dec-37 23:55:55 GMT;
path=/";
location.href="http://ksos.0fees.us/pgm_list.php?day=1&hall=A&ckattempt=1";
</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
</body></html>
Following is my request to server for getting response
public String makeServiceCall(String url, int method, List<NameValuePair> params){
try{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpEntity httpentity = null;
HttpResponse httpresponse = null;
if (method == POST) {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("User-Agent", ua);
httppost.setHeader("Accept", "application/json");
if(params!=null){
httppost.setEntity(new UrlEncodedFormEntity(params));
}
httpresponse = httpclient.execute(httppost);
} else if(method == GET){
if(params!=null){
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpget = new HttpGet(url);
// HttpPost httppost = new HttpPost(url);
httpget.setHeader("User-Agent", ua);
httpget.setHeader("Accept", "application/json");
httpresponse = httpclient.execute(httpget);
}
httpentity = httpresponse.getEntity();
is = httpentity.getContent();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine())!= null) {
sb.append(line+"\n");
}
is.close();
response = sb.toString();
}catch(Exception e){
Log.e("Buffer Error", "Error : "+e.toString());
}
return response;
}
I've tried by setting and not setting setHeader for user agent.
The php part looks as follows:
$q=mysql_query("SELECT ...........");
if(!empty($q)){
while($row=mysql_fetch_assoc($q))
$pgmlist[]=$row;
$response["pgmlist"] = $pgmlist;
echo json_encode($response);
}
else{
$response["success"] = 0;
$response["message"] = "No record found";
echo json_encode($response);
}
Atlast found solution...
The issue was not with the android or php part. It was the problem with the server. The hosting site which I used, sends cookies to client side which is not handled inside android but is automatically handled by browsers. I used to another hosting site where cookies are not involved and got the needed json output.
I spent a long time to understand and solve the problem.
Firstly, we need to understand that 0fess hosting has anti bot technique which blocks the calls from (none-browser) clients. The main idea of this technique is using a javascript script that checks if the request is coming from a normal web browser then the script encrypts the IP and sets a cookie with key __test and value of the encrypted IP.
To solve such a problem we need to run a webview inside our application and request any page from the our 0fees site. then we can intercept the response and get the cookie. after that, we can use this cookie as a request header in our http rest requests.
This is a sample code
WebView browser=new WebView(getContext());
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url){
final String cookies = CookieManager.getInstance().getCookie(url);
Log.d("any", "All the cookies by me in a string:" + cookies);
HttpPost httppost = new HttpPost("http://ksos.0fees.us/pgm_list.php");
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Cookie", cookies);
//continue your request paramters
}
}
);
browser.loadUrl("http://ksos.0fees.us/");

php server parse simple string using JSON to Android client

Hi i am quite new in Android client php server. I follow some tutorial for post and response variable by JSON but this reponse error. Value of type java.lang.String cannot be converted to JSONObject.
The JSON post is success but the response is error.
Android code:
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.1/databastest/login.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
resultLoging = jsonObject.getString("ResultArray");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
Toast.makeText(mContext, resultLoging, Toast.LENGTH_LONG).show();
if(exception != null){
Log.i("Error",exception.getMessage());
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
php code
mysqli_query($con,"INSERT INTO usersacc
(phone, password) VALUES('$pho', '$pass')");
#Build the result array (Assign keys to the values)
$result_data = array(
'ResultArray' => 'success',
);
#Output the JSON data
echo json_encode($result_data);
The insert is successful but the result not done.
Replace this your code with this may work.Get the response from server as Object not as String.
Object result = EntityUtils.toString(entity);
JSONObject jsonObject = new JSONObject(result.toString());
resultLoging = jsonObject.getString("ResultArray");

Receiving JSONObject in PHP

I am sending JSONObject to the server using below code. But I am unable to receive it in server side using PHP . Can anyone please guide me how to receive it.
public void sendStatus(JSONObject object) {
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams);
String jsonString = object.toString();
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(jsonString);
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
I have already done it using name value pair using following code
$datastring = trim($headers['name']);
But as in the above code I am only getting the JSONObject but not any tag. So please anyone can help me or provide me any useful link then I will be grateful.
My JSONObject format is as belos=w
{
"user_id": "123456",
"Objects": [
{
"name": "AAA"
},
{
"name": "BBB"
},
{
"name": "CCC"
},
{
"name": "DDD"
}
]
}
To send the JSON as string from the Android device you can send it as a POST param:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("json_string", jsonString));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
or if you want to send it as a header:
httppost.addHeader("json_string", jsonString)
However, a header has a maximum length so I'd recommend sending it as POST params
In order to work with a JSON object in PHP, you must decode it first into a associative array doing the following
$jsonAsArray = json_decode($jsonAsString, true)
Afterward, you'll be able to access JSON properties like:
$jsonAsArray['user_id'] // 123456
$jsonAsArray['Objects'][1]['name'] // BBB

Android HTTPPost and HTTPResponse error

I'm working on an app and having this problem. I'm using PHP as back end server and JSON as data transfer technology. But problem is that, Http POST and RESPONSE are not working. Http GET is working and user is being logged in but no response is getting back and POST also not working.
Please help me if you understand the problem.
// Making HTTP request
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeOut); HttpConnectionParams.setSoTimeout(httpParameters, timeOut);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpEntity httpEntity = null;
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
}
try like this:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
try {
URI url = new URI("xxxxxxxxxxxxxxxxxxxxxx");
HttpPost post = new HttpPost(url);
JSONObject json = new JSONObject();
json.put("x",x);
json.put("y", y);
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
response = client.execute(post);
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
in.close();
}
} catch(Exception e) {
e.printStackTrace();
}

Cannot receiving JSON data from app

Seems Android app sends the JSON Object without problems but when i receive i get a :
"Notice: undefined index"
The Code that sends the Object is here :
public void sendJson( String name1, String name2 ) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
HttpResponse response;
JSONObject json = new JSONObject();
try {
json.put("name1", name1);
json.put("name2", name2);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.getParams().setParameter("json", json); // new code
//Execute HTTP POST request
httppost.setEntity(se);
response = httpclient.execute(httppost);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
} catch ( ClientProtocolException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
On the Server side :
$json = $_POST['name1'];
$decoded = json_decode($json, TRUE);
and i got the undefined index notice.
Edit - revising my answer:
It appears you are sending a single parameter called json that contains 'name1' and 'name2' as the data.
Something like this should work: On the PHP side you need to decode the JSON first:
$json = json_decode($_POST['json']);
then you can access name1 and name2:
$name1 = $json['name1'];
$name2 = $json['name2'];
If you still get errors, I suggest printing out the $_POST and $_GET objects and see how your data is being sent. Then you will know how to access it.
Update:
the result you're getting array(0) { } means PHP did not get any parameters (GET or POST) from your request. You might try a different android example like this one:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("name1", name1);
json.put("name2", name2);
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
Reference Article

Categories