how to call a route of node server from android app - android

I am working on android for the first time, I just want to connect my android app with node server on a button click. my node server is
running on localhost and my mobile is also connected to the same
network. can it be possible to connect my android app with running
node server. what i have to do to call a route of server that only
prints "Hello world" in console.log of server.
If possible please help me with the code.
Thanks.
**This is my ooClick function in android.**
public void sendMessage(View view) {
name = (EditText)findViewById(R.id.name);
email = (EditText)findViewById(R.id.email);
phone = (EditText)findViewById(R.id.phone);
address = (EditText)findViewById(R.id.address);
try {
String nme = URLEncoder.encode(name.getText().toString(), "UTF-8");
String eMail = URLEncoder.encode(email.getText().toString(), "UTF-8");
String ph = URLEncoder.encode(phone.getText().toString(), "UTF-8");
String add = URLEncoder.encode(address.getText().toString(), "UTF-8");
// Create http client object to send request to server
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://192.168.0.183:3000/save?text1="+nme+"&text2="+eMail+"&text3="+ph+"&text4="+add;
//Toast.makeText(getBaseContext(),"Please wait, connecting to server."+URL,Toast.LENGTH_LONG).show();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
// Show response on activity
//content.setText(SetServerString);
Toast.makeText(getBaseContext(),"response"+SetServerString,Toast.LENGTH_LONG).show();
}
catch(Exception ex)
{
Toast.makeText(getBaseContext(),"fail",Toast.LENGTH_LONG).show();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(),"response",Toast.LENGTH_LONG).show();
}
**This is my function in node server**
app.get('/save', function(req, res){
var text1= req.param('text1');
var text2= req.param('text2');
var text3= req.param('text3');
var text4= req.param('text4');
console.log(text1+' '+text2+' '+text3);
});
I just want to print the texts in console.

You should look into using the Retrofit library. This makes it very easy to make HTTP calls from and Android app. Also, you will need the external IP address or server name in order to access the data over your network. "localhost" always refers to the current machine where the software is running. For your desktop, "localhost" is the desktop; for your Android device, "localhost" is the Android device.

Related

Connecting SQL Server database and Xamarin Android using Web API

localhost is not working, I am using a SQL Server database now, but I don't know what to put in localhost IP, I tried 10.0.2.2 and my ipv4 ip. it doesn't work too.
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
Exception
System.Net.WebException: 'Failed to connect to localhost/127.0.0.1:44330'
Code:
btnSend.Click += async delegate
{
Feedback feedback = new Feedback();
feedback.Email = edtEmail.Text;
feedback.Subject = edtSubject.Text;
feedback.Message = edtMessage.Text;
HttpClient client = new HttpClient();
string url = $"https://localhost:xxxxxx/api/Feedback?email={feedback.Email}&subject={feedback.Subject}&message={feedback.Message}";
var uri = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
var json = JsonConvert.SerializeObject(feedback);
var content = new StringContent(json, Encoding.UTF8, "application/json");
response = await client.PostAsync(uri, content);
Clear();
if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
{
Toast.MakeText(this, "Your Feedback is Saved ", ToastLength.Long).Show();
}
else
{
Toast.MakeText(this, "Your Feedback is not Saved", ToastLength.Long).Show();
}
};
}
Image of WebAPI:
Contents of WebAPI
It Depends on your Dev environment setup, if you are using a real phone then you have to make sure that your PC and your phone are on the same network and the corresponding port number is open in your PC firewall elsewhere the phone can't reach the service.

Recieving HTML file as responce instead of JSON Object through get request

I am developing an android app where user logs on to his/her account. After logging in I will receive XSRF token and Laravel Session Id to recognise the specific user. I have to send these tokens for every request I send to the API's to get the appropriate information. But when I am sending the required details as shown in the image, I am getting HTMl file as response instead of getting JSON Object. I was seriously stuck at this problem. Correct Solution may take forward the whole app.
class RegisterConnection extends AsyncTask<String,String,JSONObject> {
protected JSONObject doInBackground(String... arg0) {
JSONObject output = new JSONObject();
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 5000); //Timeout Limit
HttpResponse response = null;
try {
HttpGet get = new HttpGet(statsURL);
get.setHeader("Accept", "application/json");
CookieStore store = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("XSRF-TOKEN", XSRF);
BasicClientCookie cookie2 = new BasicClientCookie("laravel_session", laravel);
store.addCookie(cookie1);
store.addCookie(cookie2);
client.setCookieStore(store);
response = client.execute(get);
if(response!=null){
InputStream in = response.getEntity().getContent();
String resultstring = Utilities.convertStreamToString(in);
Log.i("Result1", resultstring);
output = new JSONObject(resultstring);
Log.i("Result2", output.toString());
}
} catch(Exception e) {
e.printStackTrace();
try {
output.put("sai","error");
Log.i("MainActivity", output.toString());
} catch (JSONException e1) {
e1.printStackTrace();
}
return output;
}
return output;
}
These are the server requirements
http://imgur.com/OY9Q673
This is the Output received
http://imgur.com/IB5AEcT
As far as I can tell, there is nothing wrong with your Android client code.
You are getting HTML from the server so the main reason could be that your Laravel server is rendering the views and sending you back html instead of JSON. Instead of rendering the views on the server, you should send JSON response on your Laravel server side.
Add Jsoup dependency in your gradle file
implementation 'org.jsoup:jsoup:1.11.2'
Document document = Jsoup.parse("http://imgur.com/IB5AEcT");
Elements el = doc.select("button");
Log.i("..........",""+el.attr("data-invite-details"));
Jsoup tutorial
http://jsoup.org/apidocs/org/jsoup/Jsoup.html

How to make a web request sending a HASH key and get a Response Android

I've searched everywhere on how to make this happen but with no results.
First I need to make a request to a website then send a hash (which I already have) and get a response with some data.
I was able to connect but I'm not able to use the hash key to get the data.
Can anyone help me how to do this using android?
Thanks.
I tried to follow this:Make an HTTP request with android
using a host
The solution:
final HttpClient client = new DefaultHttpClient();
final HttpPost postMethod = new HttpPost(URL);
postMethod.setEntity(new StringEntity(postData, "utf-8"));
String responseData = "";
try {
final HttpResponse response = client.execute(postMethod);
responseData = EntityUtils.toString(response.getEntity(), "utf-8");
} catch(final Exception e) {
// handle exception here
}
This is an example of what you can do:
final String URL = "http://192.168.0.100:8000/myHistory/mobile/?user=";
HttpClient client;
StringBuilder url = new StringBuilder(URL);
url.append(user);
url.append("&pwd=");
url.append(hash);
client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toString());
HttpResponse response = null;
try {
response = client.execute(get);
} catch (IOException e) {
e.printStackTrace();
}
int status = 0;
status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = "";
try {
data = EntityUtils.toString(entity);
} catch (IOException e) {
e.printStackTrace();
}
//Here you manipulate the 'data' variable, which is in HTML format.
It depends on which kind of hash you are using (SHA-N, MD5, etc) and the kind of framework you are using to build the server. Try to search on the documentation of your framework which kind of cryptographic hash function is used. Then search on internet an API that implements this cryptographic hash function on your code (e.g., Django uses PBKDF2). After that, you need to define the parameters of this function (salt, number of iterations, password (or hash)). The algorithm calculates the hash (password) using the salt and number of iterations values. So when you are trying to access a server you have to send via HTTP the hash that was generated. If this hash is the same hash generated on the server side, then the authentication is successful.

Xamarin Android Rest API to PassSlot - nameResolutionFailure

I'm using a REST API to access PassSlot in an attempt to generate a pass / coupon. It seems that when i run the program i get the error: "Error: NameResolutionFailure".
I have:
public static async Task<string> SendAndReceiveJsonRequest()
{
string responseStr = null;
string uri = "https://api.passslot.com/v1/templates/my-template-ID/pass";
// Create a json string with a single key/value pair.
var json = new JObject (new JProperty ("lastName", lastName),
new JProperty ("firstName", firstName),
new JProperty ("percentOff", percentOff),
new JProperty ("offerDescription", offerDescription),
new JProperty ("entityName", entityName),
new JProperty ("expiry", expiry));
//Console.WriteLine ("Jake's JSON " + json.ToString ());
using (var httpClient = new HttpClient ())
{
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("My-Key-Here-xxx-xxx-xxx");
//create the http request content
HttpContent content = new StringContent(json.ToString());
try
{
// Send the json to the server using POST
Task<HttpResponseMessage> getResponse = httpClient.PostAsync(uri, content);
// Wait for the response and read it to a string var
HttpResponseMessage response = await getResponse;
responseStr = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
Console.WriteLine("Error communicating with the server: " + e.Message);
}
}
return responseStr;
}
I'm running this on Android 4.4 via a Nexus 4. I'm on 3G (not wifi).
Any hints as to what might be happening here and why i'm getting the error.
In case the url request is in local network, Check if you url ip is set in the hosts device (the hosts setting of the smartphone, tablet, whatever you are using to test)
PD.
To edit the hosts setting device in android you may use this app
https://play.google.com/store/apps/details?id=com.nilhcem.hostseditor

Android: How to connect to my local MySQL?

I try to connect MySql.And can use the PostMan get data from 192.168.56.1:8080/BookBankService/rest/api/getall and when I use chorme in genymotion browse 192.168.56.1:8080/ can see the tomcat page. But when I test my code the result return null. And when I use debugger I can see the postRequest url is 192.168.56.1t:8080/BookBankService/rest/api/getall
(Ingore locahost mean 192.168.56.1 here)
public static String post(String url, String json) {
LocalhostURL ="http://192.168.56.1:8080/BookBankService/rest/api"
String result = "";
try {
String strRequest = LocalhostURL + url;
HttpPost postRequest = new HttpPost(strRequest);
postRequest.setHeader("Content-type", "application/json");
postRequest.setHeader("accept", "application/json");
postRequest.setHeader("accept","text/plain");
StringEntity s = new StringEntity(json);
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
postRequest.setEntity(s);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
Android Http request must be executed in AsyncTask or Handler.
If none, then you'll try to get the result before the execute returned a value.
Take a look at a class i created.
Java : a WebService asking embeded in a AsyncTask
where do you are testing your code?
If you're testing it in an emulator you have to replace "localhost" with "10.0.0.2" that is the IP address of the host machine.
For further info please read here: http://developer.android.com/guide/faq/commontasks.html - section "Referring to localhost from the emulated environment"

Categories

Resources