Android cannot get data when I include function.php file.But Android get data when I remove file include code in current php file.How to solve this error.I wanna use some function in function.php file.So I must use include code to call function.php.
I've no idea.is it android or php fault?
My PHP version : 5.3.10
apache version : 2.2.21
My android code:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 500000);
HttpConnectionParams.setSoTimeout(client.getParams(), 500000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject feed = object.getJSONObject("Feeds");
FeedItem.allFeedItemsList.add(new FeedItem(Integer.parseInt(feed.getString("id")), feed.getString("name"), feed.getString("post_img"), feed.getString("post_description"), feed.getString("userimage"), feed.getString("post_date"), feed.getString("post_title")));
}
Anyone can help??????????
Now i can solve my error by Encoding in ANSI. Since I Encode in UTF-8, android can't load. Now, It is fine and ok. Thanks.......
Try using this library:-https://github.com/Abhishekpalodath/FetchServerUtil-Android.git.
You can also load real-time data using this.
Related
I am trying to submit data from Android to my php server. However all the answers seem to use the deprecated apache http library. I do not want to use that, and when I tried it didn't work.
Right now it it does not seem to do anything. It seems to connect to the web server, but the server does not write any data. If I just visit the url with the browser, it will write to a file.
The php code is
<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$message=$_POST["message"];
// specify the file where we will save the contents of the variable message
$filename="androidmessages.html";
// write (append) the data to the file
file_put_contents($filename,$message."<br />",FILE_APPEND);
// load the contents of the file to a variable
$androidmessages=file_get_contents($filename);
// display the contents of the variable (which has the contents of the file)
echo $androidmessages;
?>
Then in Android studio, I am putting all of the code after a button press
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadingProgressBar.setVisibility(View.VISIBLE);
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
System.out.println("This is a test");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//Your code goes here
URL url = null;
OutputStream out = null;
String urlString = "https://mywebsite.net/php_script.php";
String data = "HelloWorld"; //data to post
try {
url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoOutput(true);
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}
Your PHP code is looking for a variable in $_POST called "message"
$message=$_POST["message"];
However in your Android code your just writing your message data to the http request body.
I suggest looking into Volley which is an HTTP library, and allows for easily making HTTP requests. This answer might also be of help.
You can use JSON and Volley for this!
<?php
$data = json_decode(file_get_contents('php://input'), true);
$filename="androidmessages.html";
file_put_contents($filename,$data["message"]."<br />",FILE_APPEND);
$reponse = array("message" => $androidmessages=file_get_contents($filename));
echo json_encode($reponse);
?>
and this in android (Kotlin):
private fun sendHtmlRequest(view: View){
val jsonobj = JSONObject()
var url = "https://URL.php"
jsonobj.put("message", "test message")
val que = Volley.newRequestQueue(context)
val req = JsonObjectRequest(Request.Method.POST, url, jsonobj,
Response.Listener { response: JSONObject ->
val messageResponse = response.getString("message")
println("response: $messageResponse")
}, Response.ErrorListener{
println("Error")
}
)
que.add(req)
}
I made a php application at the following url: http://localhost/index.php/registration/returnItemJson to return this valid json:
{"name":"test","price":30,"description":"is this working"}
In my android studio app, I am trying to read it with this:
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int response = connection.getResponseCode();
Log.d("TAG", "Response code "+response);
StringBuilder result = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while(null != (line = reader.readLine())){
result.append(line).append("\n");
}
But I am getting an IO exception by connection.GetInputStream().
It works ok when I do this with some other url that returns json, but not with localhost.
Use 10.0.2.2 instead to access your local host. Read more here
I have a .php file on the server side that works fine and extracts me results with PDO method. Therefore, when I click the file on the browser, I have no problem.
Yet, I would like this output to be put in a textView in my Android app.
Now, by the end of the php file i added:
print(json_encode(array($output)));
while in MainActivity.class I tried to get this output by parsing it through JSON.
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
}
TextView.setText(s);
Now, how do I end the JSONObject, so that "s" becomes a String that can later be added to the TextView?
Thanks in advance
Try this.
String s="";
JSONArray jArray = result.getJSONArray(result);
for(int i=0 ; i < jArray.length() ; i++) {
JSONObject json = jArray.getJSONObject(i);
s = s+"Price : "+json.getString("Price");
}
TextView.setText(s);
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/");
I have an android app which uses the multipartentity from apache httpcomponents. The app uploads a file using an HTTP request to a php script. However, the file that I am uploading (.ogg) ends up in $_POST instead of $_FILES and it looks like binary, although I could be wrong.
I have the chrome rest extension and I used it to POST a multipart/form-data request with the exact same .ogg file and the file ends up in the correct spot ($_FILES).
Android code is as follows:
// Send the file to the server.
// Create HTTP objects.
// Request.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ACTION);
// Response.
HttpResponse httpResponse;
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ContentBody cbFile = new FileBody(mediaFile, "audio/ogg");
mpEntity.addPart("file", cbFile);
httpPost.setEntity(mpEntity);
// Execute.
httpResponse = httpClient.execute(httpPost);
// Evaluate the response.
int statusCode = httpResponse.getStatusLine().getStatusCode();
// Make sure everythings okay.
if (statusCode == 200) {
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
String body = EntityUtils.toString(resEntity);
resEntity.consumeContent();
Log.d("APP_STATUS", body);
}
}
httpClient.getConnectionManager().shutdown();
And the very simple PHP script:
<?php
echo "\$_POST";
var_dump($_POST);
echo "\$_FILES";
var_dump($_FILES);
?>
Response when using the app:
Response when using the Chrome REST extension:
If anyone has any insight to what I'm failing epicly at, please let me know.
Try using the entity builder
HttpEntity mpEntity = MultipartEntityBuilder.create()
.addBinaryBody(
"file", cbFile, ContentType.create("audio/ogg"), cbFile.getName())
.build();