I'm trying to get the ip address of a host name then use it in the POST Http request URL i'm sending to
everything was working find and after adding the getByName line it suddenly crashed
So please help me and tell me exactly what could be the problem ?
Thank you in advance
Logindb.java
package com.example.loginad;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.os.Handler;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host="";
Thread mBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logindb);
login=(Button)findViewById(R.id.login);
u=(EditText)findViewById(R.id.u);
p=(EditText)findViewById(R.id.p);
res=(TextView)findViewById(R.id.res);
mBack = new Thread(new Runnable()
{
public void run()
{
try
{
InetAddress address=null;
address = InetAddress.getByName("Osama-PC");
host=address.getHostAddress();
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
boolean success = postData(params[0],params[1]);
return success;
}
protected void onPostExecute(Boolean localres){
if (localres){
res.setText("A Correct Username and Password");
}else{
res.setText("Incorrect Username or Password");
}
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
//Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}
public Boolean postData(String a,String b) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
postParameters.add(new BasicNameValuePair("mobileid",x));
// String valid = "1";
String response = null;
try {
// Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.
result = response.toString();
// res = res.trim();
result = result.replaceAll("\\s+", "");
// error.setText(res);
} catch (Exception e) {
//res.setText(e.toString());
}
return "1".equals(result);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logindb, menu);
return true;
}
}
Line 130:
Change return null; to return false;
Or something smarter would be to change
if(result!=null)
{
return result.equals("1");
}
else
{
return null;
}
to
return "1".equals(result);
Related
I was trying to load a web page on the emulator. I was trying the following code.
package com.test.scraptest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("MYAPP", "exception", e);
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
// new Toast(getApplicationContext());
Toast ts=Toast.makeText(this, "this is a message",Toast.LENGTH_SHORT) ;
ts.show();
task.execute(new String[] { "http://www.google.com" });
}
}
Problem is, when I run the application I get the following error.
I am unable to communicate to receive and send reply between the web server(which uses flask framework) and my android app whose code is as shown below.
If possible can you please post a sample server end code which might solve my problem.
package com.project.nsj;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
String userName, passkey;
EditText username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
Button login = (Button) findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//checkLogin login = new checkLogin();
//login.execute();
Intent funcs = new Intent(MainActivity.this, Functions.class);
startActivity(funcs);
}
});
}
public class checkLogin extends AsyncTask<Void, Void, Integer> {
#Override
protected Integer doInBackground(Void... params) {
userName = username.getText().toString();
passkey = password.getText().toString();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://rpihomeautomation.no-ip.biz");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("username", userName));
nameValuePair.add(new BasicNameValuePair("passkey", passkey));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpResponse response;
int status = 0;
try {
response = httpClient.execute(httpPost);
status = response.getStatusLine().getStatusCode();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == 200) {
Intent funcs = new Intent(MainActivity.this, Functions.class);
startActivity(funcs);
} else {
Toast.makeText(MainActivity.this, "Invalid password/username",
Toast.LENGTH_LONG).show();
}
}
}
}
The simplest case for handling a HTTP POST request is:
from flask import Flask, request
app = Flask(__name__)
#app.route("/data", method=("POST",))
def handle_data():
return "Hello World - you sent me " + str(request.values)
if __name__ == '__main__':
app.run()
Issue: I have two URLs that I need to call simultaneous to validate my session and directly enter to my Home (or other) pages. I am trying to call my first URL through HTTPClient execute and validate the session (Can call Login). Now second call is directly through WebView so that I can reach to my HomePage, instead of Login Page.
Below is my code. I refered lot of links and blogs but non of worked for me. I am putting my code here. Please provide your inputs if any.
package com.example.samplewebview;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieSyncManager.createInstance(MainActivity.this);
myWebView = (WebView)findViewById(R.id.webView1);
new WebViewTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class WebViewTask extends AsyncTask<Void, Void, Boolean> {
String sessionCookie;
CookieManager cookieManager;
String url1 = "http://domain.com/validateURL=sessionid";
String url2 = "http://domain.com/WebViewURLToLoad";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Boolean doInBackground(Void... param) {
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet(url1);
HttpUriRequest request = new HttpGet(url1);
try {
HttpResponse response = httpClient.execute(request);
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
System.out.println("Name : "+cookie.getName()+" --- Value"+cookie.getValue());
}
cookieManager = CookieManager.getInstance();
//cookieManager.acceptCookie();
sessionCookie = cookieManager.getCookie(url1);
//sessionCookie = new PersistentConfig(getApplicationContext()).getCookieString();
//sessionCookie = new String("test");
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
}
CookieSyncManager.createInstance(getApplicationContext()).sync();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SystemClock.sleep(1000);
return false;
}
#Override
protected void onPostExecute(Boolean result) {
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (sessionCookie != null) {
cookieManager.setCookie(url2, sessionCookie);
CookieSyncManager.getInstance().sync();
Toast.makeText(getApplicationContext(), url2, Toast.LENGTH_LONG).show();
}
//super.onPageStarted(view, url, favicon);
}
});
myWebView.loadUrl(url2);
}
}
}
I'm trying to get the data from the database for which I created a php file. It returns the name as the reply to the call. the website it Ensignweb
the program code goes like this.
The php file is like this
<?php
$connect = mysql_connect("localhost","databasename","password");
mysql_select_db("ews_app");
$query = mysql_query("select name from comment");
if(!empty($query)){
if(mysql_num_rows($query)>0){
WHILE($row=mysql_fetch_array($query)):
$comment = array();
$comment["name"] = $row['name'];
echo "$comment<br>";
echo json_encode($comment);
echo "<br>";
endwhile;
}
}
?>
The java code goes like this:
import java.io.IOException;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://www.ensignweb.com/sandbox/app/comment11.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.data);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException,IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();//return 200 if execution is success
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG);
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
But It is not displaying the json reply. I'm stucked in it from past few days.
Please help me out of it. I really need it.
I am working on with:
org.apache.http.HttpResponse;
org.apache.http.client.HttpClient;
org.apache.http.client.methods.HttpGet;
org.apache.http.impl.client.DefaultHttpClient;
i am using jsp for writing server side code.
i am unaware of the procedure of sending some value to server from my emulator.
and get a value o a string from the server response.
I mean to say... what are the methods to be used? How to use them.?
To send a HTTP GET request and retrieve response:
private static void get(final Context context, final String url) {
new Thread() {
#Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet request = Utils.createHttpRequest(context, url, true, false);
setProxyIfNecessary(context, request);
try {
HttpResponse response = client.execute(request);
Log.v("Test", "StatusCode: " + response.getStatusLine().getStatusCode() + ", Entity: " + EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
// Oh, crash
}
}
}.start();
}
private static void setProxyIfNecessary(Context context, HttpUriRequest request) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivity == null ? null : connectivity.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return;
}
String proxyHost = Proxy.getHost(context);
if (proxyHost == null) {
return;
}
int proxyPort = Proxy.getPort(context);
if (proxyPort < 0) {
return;
}
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
}
Call it by:
get(context, "http://developer.android.com/index.html");
And you will get log by logcat *:S Test:V
Notice that the new thread is to avoid blocking UI thread
Below is a code i implemented for sending username and password from android to server side JSP page. The response from the server is a json object which is then processed.The code is as given below.
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login_Menu extends Activity {
EditText usname;
EditText pass;
TextView tv;
HttpClient client;
HttpPost post;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_lay);
tv=(TextView) findViewById(R.id.login_stat_tv);
usname=(EditText)findViewById(R.id.uname);
pass=(EditText)findViewById(R.id.pass);
Button login=(Button)findViewById(R.id.login_but);
Button cancel=(Button)findViewById(R.id.cancel_but);
client = new DefaultHttpClient();
String url="http://10.0.2.2:7001/proj/login.jsp";
post = new HttpPost(url);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
new login().execute("");
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
usname.getText().clear();
pass.getText().clear();
}
});
}
private class login extends AsyncTask<String, Void, JSONObject>{
ProgressDialog dialog = ProgressDialog.show(Login_Menu.this, "", "Authenticating, Please wait...");
#Override
protected JSONObject doInBackground(String... params) {
Log.i("thread", "Doing Something...");
//authentication operation
try{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",usname.getText().toString()));
pairs.add(new BasicNameValuePair("password",pass.getText().toString()));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
int status=response.getStatusLine().getStatusCode();
if(status == 200)
{
HttpEntity e=response.getEntity();
String data=EntityUtils.toString(e);
JSONObject last=new JSONObject(data);
return last;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPreExecute(){
//dialog.dismiss();
Log.i("thread", "Started...");
dialog.show();
}
protected void onPostExecute(JSONObject result){
Log.i("thread", "Done...");
String status;
String name;
try {
status= result.getString("status");
name=result.getString("uname");
if(dialog!=null)
{
dialog.dismiss();
}
else{}
if(status.equalsIgnoreCase("yes"))
{
tv.setText("Login Successful...");
Bundle newbundle=new Bundle();
newbundle.putString("uname",name);
Intent myIntent=new Intent(Login_Menu.this,Instruction.class);
myIntent.putExtras(newbundle);
startActivity(myIntent);
}
else{
tv.setText("No User Found, please try again!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}