Retrieving string from MySQL-DB with java (eclipse) through json - java

I'm trying to program a Login-System for Android (in Eclipse) and have to get the data from an external MySQL-DB.
Source I took the code for it: Connecting to MySQL Database
The Website I'm trying to fetch the data from is here.(I know there are some safety issues, blabla, this is not my problem right now^^)
The Problem I have, is when I try to run the Application, The Error "No Password found".
This Error is catched within this Code:
ArrayList<String> passwort = new ArrayList<String>();
ArrayList<String> benutzer = new ArrayList<String>();
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
passwort.add(json_data.getString("pw"));
benutzer.add(json_data.getString("benutzer"));
}
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("arrayBenutzerExtra", benutzer);
intent.putExtra("arrayPasswortExtra", passwort);
startActivity(intent);
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Password found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
As addition, here is the code where I connect with the website, but it doesn't seem to be the problem, though I don't get an error message about that!
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://winklermarkus.at/appconnection.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
The Code of the .php file is here:
$sql_pw = "SELECT ". "Passwort ". "FROM ". "benutzerdaten ";
$result_pw = mysql_query ($sql_pw);
$data_pw = mysql_fetch_array ($result_pw);
$pw = $data_pw["Passwort"];
$sql_benutzer = "SELECT ". "Email ". "FROM ". "benutzerdaten ";
$result_benutzer = mysql_query ($sql_benutzer);
$data_benutzer = mysql_fetch_array ($result_benutzer);
$benutzer = $data_benutzer["Email"];
print(json_encode($pw));
print(json_encode($benutzer));
mysql_close();
?>
as Perception mentioned, I don't get valid JSON output, could this possibly be in relation with me, trying to transmit 2 strings at once?

Your PHP code is not doing what you think it's doing. I cannot recommend a fix to it as you've created a significant security hole.
As an alternative strategy, instead of sending all the passwords and all the emails to the client (in an unassociated fashion no less), send the clients hashed password and email to the service (over SSL). Then on the service side query if you have the combination of email/pass in the database. If you do return login success, otherwise return login failed.

Related

Cannot add attachment to new RT ticket

I'm currently using RT 4.4.3 in a project and I'm trying to create a new ticket with an attachment, using Java code.
I tried to follow the instructions provided by this BestPractical resource hosted on GitHub and specified in this list of pulls.
The code fragment that tries to perform the operation is the following:
PostMethod mPost = new PostMethod(TicketListConstants.SEGNALAZIONI_RTIR_URI + "/ticket");
mPost.setRequestHeader("Content-type", "application/json");
mPost.setRequestHeader("Authorization", TicketListConstants.SEGNALAZIONI_RTIR_TOKEN);
/*String json = ;
NameValuePair[] data = {
new NameValuePair("content", json)
};*/
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
File file = uploadRequest.getFile("fileName");
String filename = uploadRequest.getFileName("fileName");
byte[] filecontent = this.encodeBase64(file);
mPost.setRequestBody("{ \"Queue\": \"Infosharing\", \"Subject\": \""+subject+"\",\"From\":\""+currentUser.getEmailAddress()+"\",\"To\":\"test#liferay.com\",\"Owner\":\""
+currentUser.getEmailAddress()+"\",\"Requestor\":\""+currentUser.getEmailAddress()+"\",\"Content\":\""+description+"\",\"AttachmentsContents\":[{\"FileName\":\""+filename+"\",\"FileType\":\"application/pdf\",\"FileContent\":\""+filecontent+"\"}]}");
HttpClient cl = new HttpClient();
String result = "";
String newId = "";
try {
cl.executeMethod(mPost);
result = mPost.getResponseBodyAsString();
if (result != null) {
JSONObject json = null;
try {
json = JSONFactoryUtil.createJSONObject(result);
} catch (JSONException e) {
_log.error("Error extracting ticket info: "+e.getMessage());
}
newId = json.getString("id");
}
} catch (UnsupportedEncodingException e){
_log.error("Error in searching tickets: "+e.getMessage());
} catch (IOException io) {
_log.error("Error in searching tickets: "+io.getMessage());
}
So the JSON I'm sending to RT is the following:
{ "Queue": "Infosharing", "Subject": "Tutto in uno","From":"test#liferay.com","To":"test#liferay.com","Owner":"test#liferay.com","Requestor":"test#liferay.com","Content":"Aggiungo tutto in un solo passaggio","AttachmentsContents":[{"FileName":"prova.txt","FileType":"plain/text","FileContent":""}]}
The problem is that the ticket is correctly created but no attachment is added.
I also tried to perform the same using SOAPUI but no attachment is added to the ticket even if the response is without any error.
Could somebody help me what I'm doing wrong?
EDIT 2019-06-10: since it seems that, as reported here, at least till the end of December 2018:
CREATING ATTACHMENTS Currently RT does not allow creating attachments
via their API.
See https://rt-wiki.bestpractical.com/wiki/REST#Ticket_Attachment
but it should be possible, as a temporary workaround, to post attachments to ticket's comments, can anybody help finding a solution to this problem?
Since I cannot test your code, I suggest you to use HttpClient 4, I provide below a sample code snippet. Modify the code as per your requirement and try to check.
HttpPost post = new HttpPost("http://rtserver.com");
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
HttpEntity entity = builder.build();
post.setEntity(entity);
HttpResponse response = client.execute(post);

Extracting data from a HTML response - Android

In my Android app, I am accessing a website using GET requests to its API. The request returns an HTML file with a variety of user information. From this, I want to know how to extract user data, such as their profile pictures, their data and such. I would like to know how I could access and retrieve this data to display in my app.
Any help will be greatly appreciated.
Thanks in advance.
If you just want to be able to access the data you could get the api to output in in JSON format and read the JSON from your app, something like:
public void getData(){
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://website.com/download.html");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
names.add(" " + json_data.getString("name"));
age.add(" " + Integer.toString(json_data.getInt("age")));
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
The easiest way to go for HTML Parsing to extract and manipulate the data then go for JSoup......
See this link for more details:
http://jsoup.org/
The simplest way would be to display the HTML data in a WebView.

How to get all permissions for web service in android?

I have created an android application using java, php(backend) and mysql(database). I have placed my backend php code and the database on Linux hosting server. My problem is that I can only read the data from the database, i.e., my application can fetch the data from the server, but it couldn't make any changes to the fetched data and also I get errors when I run using the server, but when I placed the database and code in local system it works perfectly on the localhost, but when placed in server it can only read the data but not insert, update or delete the data. I have already given full privileges to the database in the server. Can anyone please help me regarding this aspect?
I think the server doesn't accept requests from outsider like mobile. So my question is
what do we need to do such that the server accepts requests from mobile side?
PS: I have given full privileges to the database in server and also I have added Internet permission in the android manifest file.
#Lie Ryan: As per your request, here is my code to connect to server:
protected List<List<String>> callWebServer(String queryString, String statement){
List<List<String>> stringList = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("query", queryString));
nameValuePairs.add(new BasicNameValuePair("statement", statement));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(WEB_SERVICE_URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,responseHandler);
JSONObject json = new JSONObject(responseBody);
if(statement.equals(DB_SELECT_STATEMENT) || statement.equals(DB_INSERT_STATEMENT)){
List<String> queryStrings = null;
// parsing query
if(statement.equals(DB_SELECT_STATEMENT)){
queryStrings = splitQuery(queryString);
JSONArray jArray = json.getJSONArray("output");
if(jArray.length() > 0)
stringList = new ArrayList<List<String>>();
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String rowData = json_data.getString("rowData");
if(rowData.equals("nothing")){
// Toast.makeText(getBaseContext(), "No record found", Toast.LENGTH_LONG).show();
}else{
JSONObject getClassNameObject = new JSONObject(rowData);
List<String> tempStringList = new ArrayList<String>();
for(String valueStr:queryStrings){
if(valueStr.contains(".")) valueStr = valueStr.split("\\.")[1];
tempStringList.add(getClassNameObject.getString(valueStr));
}
stringList.add(tempStringList);
}
}
}else{
JSONArray jArray = json.getJSONArray("output");
stringList = new ArrayList<List<String>>();
JSONObject json_data = jArray.getJSONObject(0);
stringList.add(getList("mn", json_data.getString("rowData")));
}
}
//Toast.makeText(getBaseContext(), "Event Added Successfully", Toast.LENGTH_LONG).show();
}catch(ArrayIndexOutOfBoundsException e){
}catch(Exception e){
Log.e("log_tag", "Error in http connection:"+e.toString());
}
and the php code to handle the request is:
<?php
include "connect.php";
if($_POST["statement"] == "select"){
$booleanRow = true;
// for select statements
$db_output = mysql_query($_POST["query"]));
while($row=mysql_fetch_array($db_output, MYSQL_ASSOC)){
$output[] = array('rowData'=>$row);
$booleanRow = false;
}
if($booleanRow){
$row = "nothing";
$output[] = array('rowData'=>$row);
}
print(json_encode(array('output'=>$output)));
}else{
// for insert, update and delete
mysql_query($_POST["query"]);
$row = mysql_insert_id();
$output[] = array('rowData'=>$row);
print(json_encode(array('output'=>$output)));
}
mysql_close($link);
?>
Thanks in Advance.
To allow applications to open network sockets you need to set the 'android.permission.INTERNET' permission in your android manifest file (AndroidManifest.xml):
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
For a list of more permissions see the Manifest.Permission class.

MySQL PHP JSON null text

I found a problem with some results of a search on a DB. When, some fields have extra characters like "ü", the field return as null so it appear as null on the search. My code is like this:
the php Script
$q=mysql_query("SELECT * FROM PRODFAR WHERE ARTI LIKE '%".$_REQUEST['search']."%'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
the JSON PARSER constructor:
public class JsonParser {
static InputStream is = null;
static JSONObject json_data = null;
static String result = "";
// constructor
public JsonParser() {
}
public JSONArray getJSONFromUrl(ArrayList<NameValuePair> nameValuePairs, String url) {
//http post this will keep the same way as it was (it's important to do not forget to add Internet access to androidmanifest.xml
InputStream is = null;
String result ="";
JSONArray jArray = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response that we receive from the php file into a String()
try{
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();
result = sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// try parse the string to a Json object
try {
//json_data = new JSONObject(result);
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return Json String
return jArray;
}
}
any hint of how I can solve this?
update: as long as I cannot pass it with JSON, because it only admits UTF-8 characters. I think that one of the possible solutions is to convert the text through PHP into UTF-8 encoding archive, and the other is to use an alternative to JSON that supports other encodings. so I would like to try the first one. so if any know a good algorithm to covert the encoding of a text to UTF-8 using PHP will help to. Also other hints or tips of possible directions to find a solution are welcome please comment on this post any Idea is welcome
SOLVED
I solved it encoding it to UTF-8, it changed my characters like "ü" to something like u\000f, but the java editor show it as iso-8859-1 like Ü when it's showed on the screen. The edited PHP code have the following lines after the query:
$q=mysql_query("SELECT * FROM PRODFAR WHERE ARTI LIKE '%$search1%'");
while($e=mysql_fetch_assoc($q)){
$e['ARTI'] = utf8_encode ( $e['ARTI'] );
$e['DESC'] = utf8_encode ( $e['DESC'] );
$e['PRESENT'] = utf8_encode ( $e['PRESENT'] );
$output[]=$e;
}
print(json_encode($output));
JSON only support UTF8. So try using utf8_encode() / utf8_decode() for conversion.
At first blush, I'd guess it as an encoding issue. Make sure your tables are UTF-8 and also that your views are the same.
Also: Please don't put $_REQUEST data directly into your SQL. That will come back to haunt you.

How to connect Android emulator with local mysql database

I want to connect mysql database locally with android emulator. I used http GET and POST methods for accessing data from Google Cloud SQL with app engine but i want to connect it with locally using phpmyadmin..
when i use following code it show Toast for connection failed
String result = "";
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","Hammad"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/myApp/read_data.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
}
//convert response to string
try{
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");
Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("user_id")+
", Username: "+json_data.getString("username")+
", Name: "+json_data.getInt("name")+
", City: "+json_data.getInt("city")
);
Toast.makeText(getApplicationContext(), "JsonArray pass", Toast.LENGTH_SHORT).show();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
}
}
If you're running this within the emulator localhost:3306 won't work. Replace that with the IP address of the machine running MySQL. So for example if your local dev machine (running MySQL) uses IP 192.168.0.10, change that to 192.168.0.10:3306.
Just to expand a bit - when you attempt to access http://localhost:3306 within the emulator (or even on a device) it tries to connect to the port 3306 on the loopback address (on the emulator/device). You obviously don't have the SQL service running on the android so this doesn't make sense.
Also, depending on your OS configuration, you may have to open port 3306 in your firewall.
Edit: Warren's tip (below) leads me to the details in the Android docs. May want to stick with 10.0.2.2 if you don't want to mess around with your OS' firewall.

Categories