Hi I'm setting up a new test server by mysql and want to create a test app in android that get the username and password from client and if they correctly inputted, app show toast( yeaah + username )
but it show js and html code :(((
and at last of this toast is:
<noscript> this site requires javascript to work , please enable javascript in your browser or use a browser with javascript support </noscript>
This is the main activity :
package com.example.server;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static String Res="";
public static String res="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetData("http://aysam1388mohammad.gigfa.com/test1.php", "mohammadreza").execute();
Button btn=(Button) findViewById(R.id.Main_BTN_Click);
final TextView txt=(TextView) findViewById(R.id.Main_Txt);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
txt.setText(Res+"\n"+res);
}
});
}
}
this is the GetData class :
package com.example.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.AsyncTask;
public class GetData extends AsyncTask{
private String LInk;
private String USer;
public GetData (String Link,String User) {
LInk = Link;
USer=User;
}
protected String doInBackground(Object... arg0) {
try{
String data=URLEncoder.encode("Username1","UTF8")+"="+URLEncoder.encode(USer,"UTF8");
URL Link=new URL(LInk);
URLConnection Link_Connect=Link.openConnection();
Link_Connect.setDoOutput(true);
OutputStreamWriter WR=new OutputStreamWriter(Link_Connect.getOutputStream());
WR.write(data);
WR.flush();
BufferedReader Reader = new BufferedReader(new InputStreamReader(Link_Connect.getInputStream()));
StringBuilder Sb=new StringBuilder();
String Line=null;
while((Line=Reader.readLine())!=null) {
Sb.append(Line);
}
MainActivity.res=Sb.toString(); // "res"
MainActivity.Res="Yeeeeeeah"; // "res"
}catch(Exception e) {
MainActivity.Res="nooooo"; // "res"
}
return "";
}
}
I'm sorry because of my terrible English and thank you that read this stack.
oh I forget to say that I used a php file in mysql database to connect with my app.
this is php file:
<?php
$conect=mysql_connect("sql210.gigfa.com","gigfa_23465941","13882345");
mysql_select_db("gigfa_23465941_Db1",$conect);
$User=$_POST['username'];
$SqlQ="select * from User where Username='$User' ";
$result=mysql_Query($SqlQ);
$Row=mysql_fetch_array($result);
if($Row[0]){
print("yeah \n");
}else {print("noo");
}
print $Row[1];
mysql_close($conect);
?>
Related
im working on this program ,which i have an Android app that uses Nodejs server.the host is -https://rocky-thicket-82184.herokuapp.com.
now, im trying to just send and recieve a post request . but it seems to not
work.
in the server side i get an error like : cannot GET/.
and in the client side i get :error exeption https://rocky-thicket-82184.herokuapp.com.
I cannot find the problem ,i feel like i'm missing something ...
here is my Android mainActivity.java:
package com.example.shanijoffe.hungry_monkey;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.stormpath.sdk.Stormpath;
import com.stormpath.sdk.StormpathConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import static com.loopj.android.http.AsyncHttpClient.log;
public class MainActivity extends AppCompatActivity
{
EditText user_name_edit;
EditText password_edit;
Button loginButton;
String user;
String user_pass;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name_edit=(EditText)findViewById(R.id.txt_usrname);
password_edit=(EditText)findViewById(R.id.txt_password);
loginButton=(Button)findViewById(R.id.btn_login);
Log.i(TAG,"before connection");
}
public void OnClick(final View view) {
view.setEnabled(false);
user=user_name_edit.getText().toString();
user_pass=password_edit.getText().toString();
new SendPostRequest().execute();
//
//
}
public class SendPostRequest extends AsyncTask<String, Void, String>
{
String user_name=user_name_edit.getText().toString();
String user_pass=password_edit.getText().toString();
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
Log.e("MainActivity", "in SendPostRequest ");
URL url = new URL("https://rocky-thicket-82184.herokuapp.com");
InputStream inp = (InputStream) url.getContent();
Log.e("stream",inp.toString());
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", user);
postDataParams.put("password", user_pass);
Log.e("params", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
int responseCode;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"))) {
String encoded_string = getPostDataString(postDataParams);
Log.e("encoded", encoded_string);
//writer.write(getPostDataString(postDataParams));
writer.write(postDataParams.toString());
writer.flush();
writer.close();
}
os.close();
responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.i("MainActivty",sb.toString());
return sb.toString();
} else {
return new String("false : " + responseCode);
}
}
catch (Exception e)
{
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
public String getPostDataString(JSONObject params) throws Exception
{
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
}
and here is the nodejs code:
var express=require('express');
var bodyParser=require('body-parser');
var app=express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.post('/',function(req,res){
console.log(req.body);
if (!req.body)
return res.sendStatus(400)
res.send('welcome, ' + req.body.user)
});
app.listen(process.env.PORT || 3000)
can anyone take a look and see if they can help ?
Thanks alot :)
restful service in android authenticating and connecting it to the url
new to android
unable to get the output : username password and connecting to the url
package com.example.newrestapi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText password,userName;
Button login;
ProgressBar progressBar;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
password=(EditText) findViewById(R.id.editText2);
userName=(EditText) findViewById(R.id.editText1);
login=(Button) findViewById(R.id.button1);
//progess_msz.setVisibility(View.GONE);
progressBar=(ProgressBar) findViewById(R.id.progressBar1);
progressBar.setVisibility(View.GONE);
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
String s1=userName.getText().toString();
String s2=password.getText().toString();
new ExecuteTask().execute(s1,s2);
}
});
}
class ExecuteTask extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
String res=PostData(params);
return res;
}
#Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
//progess_msz.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), result, 50000).show();
}
}
public String PostData(String[] values) {
String s="";
try
{
HttpClient httpClient=new DefaultHttpClient();
HttpGet httpGet=new HttpGet("http://myrul");
HttpResponse httpResponse= httpClient.execute(httpGet);
HttpEntity httpEntity=httpResponse.getEntity();
s= readResponse(httpResponse);
}
catch(Exception exception) {}
return s;
}
public String readResponse(HttpResponse res) {
InputStream is=null;
String return_text="";
try {
is=res.getEntity().getContent();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuffer sb=new StringBuffer();
while ((line=bufferedReader.readLine())!=null)
{
sb.append(line);
}
return_text=sb.toString();
} catch (Exception e)
{
}
return return_text;
}
}
login authentication using android restful services
I want to parse html pages and extract data but when I tried to connect with Jsoup it throws errors. when I connected using httpclient [String s = EntityUtils.toString(response.getEntity(), "UTF-8");] there was no problem the html page content I was able to store into a string. But with Jsoup I am not able to do it.Am I making some error?
package com.example.flashcardsdemo;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.w3c.dom.Element;
//import com.example.flashcards.MainActivity.Gethtml;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
Gethtml Ght = new Gethtml();
Ght.execute();
}
public class Gethtml extends AsyncTask {
ProgressDialog dialog;
String UrlLink = "http://en.wikipedia.org/";
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setTitle("Loading");
dialog.setMessage("Html....");
dialog.show();
}
#Override
protected Object doInBackground(Object... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(UrlLink);
HttpResponse response = client.execute(request);
StatusLine line = response.getStatusLine();
int statuscode = line.getStatusCode();
if (statuscode != 200) {
return null;
}
Document doc = Jsoup.connect(UrlLink).get();
}
catch (Exception e) {
Log.v("Error", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Object result) {
dialog.dismiss();
}
}
}
LogCat image: [1]: http://i.stack.imgur.com/Q6bDv.png [2]: http://i.stack.imgur.com/TBxUB.png
I found "NoClassDefintionFound" error for Jsoup from logcat.
Got to Java build path of your android project >> Order and Export tab >> Check your Jsoup library.
After checking the Jsoup library , select it and move it up using UP button.
Then clean the project and run it again.
So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.
I have spent a lot of time trying to make this code work, and in its current state it almost exactly mirrors the code I found at https://stackoverflow.com/questions/3482583/apache-ftpclient-failing-to-download-larger-files. I am also using apache commons net.
for some reason my application never gets past the client.connect step, even when i plug in other IP addresses of ftp servers that should work.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class FtpClientService extends Activity {
//static int fail;
public FtpClientService(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.ftp);
FtpConnect();
}
public static void FtpConnect(){
String userName="usrname";
String passWord = "password";
String ftpAddress = "127.0.0.1"; //this isnt the ip address I was using...
String retrieveFromFTPFolder = "/Pictures/";
String strLine;
DataInputStream inputStream = null;
BufferedReader bufferedReader = null;
FTPClient client = null;
FTPFile[] ftpFiles = null;
int reply;
try{
client = new FTPClient();
client.setListHiddenFiles(true);
client.connect(ftpAddress); //this right here is where it fails
client.login(userName, passWord);
client.setFileType(FTP.BINARY_FILE_TYPE);
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (Exception e) {
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f) {}
}
}
finally{
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f){}
}
}
}
public static void main(String[] args) {
FtpConnect();
}
Thanks in advance!
In the connect method, pass it a constructed InetAddress with appropriate address and port.
Also, don't perform FTP connection on main thread, consider using AsyncTask.
Try using this:
client.connect(InetAddress.getByAddress(ftpAddress,new byte[]{127,0,0,1}));