I have an Android java method that calls a remote php to insert data into a mysql table.
This is java code client side:
public static void insert(String email1, String email2) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("email1", email1));
nameValuePairs.add(new BasicNameValuePair("email2", email2));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myserver:8080/insert.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//How to catch and print php echo() here??
}
and this is the insert.php server side (re-edited):
<?php
$mysqli_connection = new mysqli("localhost:3306", "root", "password", "mydb");
if ($mysqli_connection->connect_errno) {
echo ("Connection Failure");
exit();
}
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("INSERT INTO `mytable` (`email1`, `email2`) VALUES (?,?)")) {
echo 'Success';
$stmt->bind_param("ss", $_GET['email1'], $_GET['email2']);
$stmt->execute();
$stmt->close();
} else {
echo 'Error Inserting Content';
}
$mysqli->close();
?>
When I call my java insert() method, no exception is returned, but no insert is done and mytable is empty.
1) What is wrong?
2) How can I see which error occured? How can I see a "log" of the the php-side execution?
Thank you very much.
Geltry
use backtick instead of single quote for column names and/or tableNames
INSERT INTO mytable(`email1`,`email2`) VALUES('$email1','$email2')
when do you use backtick?
when column name or table name is a Reserved Keyword in MySQL
when it contains space,
eg,
CREATE TABLE `hello word`(`Record ID` INT,....)
and you query is vulnerable with SQL Injection, please take time to read the article below
How can I prevent SQL injection in PHP?
Look into your HttpResponse/HttpEntity. There you should see either 'Success' or 'Error Inserting Content'. You can also add the concrete errno and error string in your response to see, what's really going wrong.
You also mix HTTP POST and HTTP GET in your request. On the client side you use a HttpPost object and on the server side you expect the _GET variables to be set. You must use either GET or POST on both sides. Otherwise client and server won't understand each other.
With HttpEntity.getContent() you can read from an InputStream. Another approach would be to use EntityUtils.toString() to get a string representation of the response's content.
Related
I feel very sorry to ask that question because I am pretty sure that this was already asked. But by searching here or with google I always land at sites where REST services with incoming requests are tested.
In my case I have a method that sends a request to a server. I want to test if that request is correct. I use java and spring boot. Every time I test that, the request is send to the server. Can I intercept that?
public void buy(double price) {
final String timestamp = String.valueOf(System.currentTimeMillis());
final String amount = String.valueOf(observer.requestedAmount);
final String ressouce = GetValuesTypes.getRessource("user").get(observer.getRelatedUser);
String queryArgs = "wwww.doSomething.com/" + ressouce;
String hmac512 = HMAC512.hmac512Digest(queryArgs);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(GetValuesTypes.getURL());
post.addHeader("Key", GetValuesTypes.getKey());
post.addHeader("Sign", hmac512);
try {
post.setEntity(new ByteArrayEntity(queryArgs.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
System.out.println("Exception in run");
}
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("command", "order"));
params.add(new BasicNameValuePair("ressource", ressource));
params.add(new BasicNameValuePair("rate", String.valueOf(rate)));
params.add(new BasicNameValuePair("amount", amount));
params.add(new BasicNameValuePair("timestamp", timestamp));
try {
post.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
Scanner in = new Scanner(entity.getContent());
String orderNumber = "";
while (in.hasNext()) {
orderNumber = in.nextLine();
}
String[] findOrderNumber = orderNumber.split(".");
long lastOrderNumber = -1;
try {
lastOrderNumber = Long.valueOf(findOrderNumber[3]);
} catch (NumberFormatException exception) {
System.out.println("NumberFormatException");
} finally {
if (lastOrderNumber != -1) {
observer.setOrderNumber(lastOrderNumber);
}
}
in.close();
EntityUtils.consume(entity);
httpClient.close();
} catch (IOException e) {
System.out.println("Exception occured during process");
}
}
I would appreciate your help very much.
This is a typical question that are faced by all the people who are trying to write tests for their code (and this also means that there are many articles on the net about how to do it).
In this particular case, I see two ways:
if you want to write a unit test: instead of creating HttpClient, you should make it configurable, to be able to substitute it by mock in the unit tests. You can hold it as a class member or provide as a second argument to buy() method. Later, in a unit test, you need to provide a fake version of HttpClient (mock) that allows you to inspect its arguments to ensure that they're equal to expected.
if you want to write an integration test: you need to run a fake service that behaves like a real server but also allows to inspect received requests. In an integration test, you need to configure HttpClient to connect to this fake server and after that check that the server received request from a client.
How to implement this, is up to you and technologies with that you're familiar to.
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 am in a ditch since last few days trying out to get this,but not able to bring out any desired results.I will try to make myself clear that what i am looking for in following points:
I am working on android app,that will update the location of the user on the server using servlets(on my localhost).There is no problem regarding this,all is working fine.
The real problem that came in my way was when i was trying to get response from server back to android device,i just want to return a simple string,or something like that,Most likely a parameter,that will be utilized by the android app.Then i came to know about the json thing that i have to use it for doing what i am looking for.I have searched a lot about it,found some code too,but not able to use it well,
So my questions are
Is it possible to retrieve response from the servlet,and extract the required values from it without using json or any parsing technique,because i needed something like a single string only.
HttpClient client=new DefaultHttpClient();
HttpGet request=new HttpGet();
URI address=new URI("http://xxx.xxx.xxx.xxx:8080/MyServlet");
request.setUri(address);
HttpResponse response=client.execute(request);
The code from the android device requesting the response and the servlet are shown above,however when i call the toString method on response.toString() in android device,it yield me a string with some sequence of numbers,which are of no use to me.
HELP! HELP! HELP!
A simple example of it might help me up,
You could use a servlet that generates plain text result without any encoding technique.
On the server side, just replace your doGet function to look like that:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
On the client side, you could use the following code:
try {
final HttpClient httpClient = new DefaultHttpClient();
final HttpGet httpGet = new HttpGet("http://SERVLET_URL/");
HttpResponse response = httpClient.execute(httpGet);
final HttpEntity entity = response.getEntity();
Log.i(TAG, "Servlet Result: " + EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
Log.e(TAG, "ClientProtocolException", e);
} catch (ParseException e) {
Log.e(TAG, "ParseException", e);
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
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.
I am trying to make a login script for my android application, the script will send my email and password to the PHP server, verify the login and then create a PHP session so that the user stays logged in. This is my code,
HttpPost httppost = new HttpPost("http://server.com/login.php");
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
public String login() {
String userID = "";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "e#e.com"));
nameValuePairs.add(new BasicNameValuePair("password", "admin"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
userID = EntityUtils.toString(response.getEntity());
//Log.v("Login response", "" + userID);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return userID;
}
This script successfully sends data to my server and my PHP successfully logs the user on. I have placed "HttpClient httpclient = new DefaultHttpClient();" outside my main login method. This has helped store the session until I call upon another class, then it just resets the session again. So I am wondering how I can alter the code so that "httpclient" is somehow stored so I can keep the session and stay logged into my server. Thank you!
Android Http get Session Cookie
Get the cookie session ID and use that cookie in the next requests to the server.
Another way is to make your php code echo a string containing the session_id in its response to login.Let the android app retrieve this id and store it. Any future requests can be made by using post method with sess_id=stored id
<?php
if(isset($_POST['sess_id']))
{
session_id($_POST['sess_id']); //starts session with given session id
session_start();
$_SESSION['count']++;
}
else {
session_start(); //starts a new session
$_SESSION['count']=0;
}
echo session_id();
?>