I have opened up 4 months old android project and I faced some problems which I didn't have before.
I have a web-service http://tojesttest.byethost22.com/PizzaService/getAndroidOrders.php
which gets me JSONArray when I open it in a browser, but when I call it from inside of android app it gets me in return:
10-16 21:29:35.021 18477-18565/com.example.tomek.pizzaservice E/HTTP: Success!<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("cd6163c2d295cc64f22c62356ba045f4");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";location.href="http://tojesttest.byethost22.com/PizzaService/getAndroidOrders.php?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>
I've tried to enable java script in android Internet browser but it was already turned ON.
Piece of code that I'm using:
private static JSONArray loadFromDatabase(String phpFileAddress){
JSONArray jsonArray = null;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(phpFileAddress).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.e("HTTP", "onFailure");
}
#Override
public void onResponse(Response response) throws IOException {
try {
final String jsonData = response.body().string();
if (response.isSuccessful()) {
Log.e("HTTP","Success!" + jsonData);
} else {
Log.e("HTTP","Zła odpowiedź serwera.");
}
}
catch (IOException e) {
Log.e("HTTP","Zła odpowiedź serwera.");
}
}
});
return jsonArray;
}
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'm trying to retrieve the total number of correct answers answered by the students from different countries.
I'm using JSON to link to my php then to my database. But i seems to can't read the spaces in between words. For example, the country name is "Czech Republic" in the database. However when i echo, it shows me "Czech".
The $country in the php code is from the android studio, where i sent a url link Config.LEADERSHIPBOARD_URL_ME + country; to get connected to the database.
This is my php code:
<?php
$country = $_GET['country'];
require "conn.php";
$sql_mcq = "SELECT * FROM mcqparticipator WHERE country = '".$country."'";
$r_mcq = mysqli_query($conn,$sql_mcq);
$result = array();
$mcqCount = 0;
if($r_mcq)
{
while($row = mysqli_fetch_array($r_mcq))
{
if(($row['correctAns'] == "1"))
{
$mcqCount++;
}
}
array_push($result,array(
"McqCount"=>$mcqCount,
"Country"=>$country));
echo json_encode(array("result"=>$result));
}
else
{
echo "No connection";
}
$conn->close();
?>
And this is my code from android studio:
// Description: This method will generate a url and send a request
// This method will call showJSON() method to start sending the response
private void getData(){
loading = ProgressDialog.show(getActivity(), "Please wait...","Fetching", false, false);
url = Config.LEADERSHIPBOARD_URL_ME + country;
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
Toast.makeText(getActivity(), "Country in studio: " + country, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Country in database: " + dcountry, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "Mcq count: " + McqCount, Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(getActivity(),"No existing question", Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue= Volley.newRequestQueue(getActivity());
requestQueue.add(stringRequest);
}
// Description: This method will generate a response using JSON via php.
// Retreive and compare the participants answer with the correct answer
public void showJSON(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
McqCount = collegeData.getString(Config.MCQ_COUNT);
dcountry = collegeData.getString("Country");
} catch (JSONException e) {
e.printStackTrace();
}
}
Appreciate if someone could help me, thank you!
I want to get a response from a URL that has to do ajax requests to get and update the page without refreshing it.
My problem is when I want to receive its response with the volley library. In onResponse I just receive php code!!?
here is my code:
RequestQueue queue = Volley.newRequestQueue(getActivity());
final String test= "MY URL";
StringRequest stringRequest = new StringRequest(Request.Method.POST, test,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
popup.dismiss();
Log.e("response", response );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
popup.dismiss();
}
});
queue.add(stringRequest);
I tried with Request.Method.POST and Request.Method.GET but no difference.
NOTE:
I only can see the response of this URL when I am using chrome and 'Allow-Control-Allow-Origin' extension is installed.
Can we post JsonObject or JsonArray using Android volley to the server?If yes can anyone please send the working sample.
If i post string then it works fine but i have some problem while posting jsonObject or jsonArray.
Yes you can. The JSON is added to the body of a POST request, like this:
JSONObject jsonObject; // your JSON here
requestQueue.add(new JsonObjectRequest(Method.POST, url, jsonObject, listener, errorListener);
Yes, just add data to JSONObject and pass that object in the request.
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("password", password);
RequestQueue queue = Volley.newRequestQueue(context);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("volley", "response: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("volley", "error: " + error);
}
});
Currently I am using Spring MVC architecture having JSP as a VIEW. At present, the website is build with PHP .
<form:form method="POST" commandName="user">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
<td><form:errors path="name" cssClass="error" /></td>
</tr>
</table>
</form>
I need to invoke the above JSP Post function from PHP page and retrieve the result back to the PHP page. How can I achieve this?
Help.Please.
There is couple of ways to deal with your situation, the simplest way is that in the action jsp or servlet, create a URLConnection to retrieve the result:
try {
URL url = new URL("http://domain.com/something.php");
URLConnection urlConnection = url.openConnection();
Map<String, List<String>> headers = urlConnection.getHeaderFields();
Set<Map.Entry<String, List<String>>> entrySet = headers.entrySet();
for (Map.Entry<String, List<String>> entry : entrySet) {
String headerName = entry.getKey();
System.out.println("Header Name:" + headerName);
List<String> headerValues = entry.getValue();
for (String value : headerValues) {
System.out.print("Header value:" + value);
}
System.out.println();
System.out.println();
}
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = bufferedReader.readLine();
while (line != null) {
System.out.println(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The another way is using ajax for your request, you don't need to start from scratch but using one of well known framework such as jquery or extjs ...
Using extjs you can request to php page:
yourform.doAction('submit',
{
url: 'something.php',
success: function(form, action)
{
//To do: when success
},
failure: function(form, action)
{
}
});
Enjoy coding!