Sending Api requests from Android to Localhost - android

Im trying to get my android app in my phone to talk with the spring boot backend. I tried setting the ip address of my pc instead of using it as the "localhost". but it does not work though.
Any idea on how to fix this and get by application to sent requests to my spring boot backend?
This is my code for the api call and the client.getProxy() will retrieve the saved "http://......" (PS: im using the volley library)
JsonObjectRequest authenticate = new JsonObjectRequest(
Request.Method.POST, client.getProxy() + "/authenticate", auth,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
resp = response.toString();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
resp= "FAILED ";
}
}
Thanks in advance.

Instruction for the local host to physical mobile.
your mobile and laptop must be connected on same WiFi. Then you need to set your laptop ip on link from the command prompt.command ipconfig and get ipv4address from the result

Related

Android Volley doesn't seem to be able to connect to Flask localhost address for GET method for return String from Flask?

This is the Android Volley code :
// I already add the uses-permission for INTERNET to manifest
<uses-permission android:name="android.permission.INTERNET" />
// and add volley to gradle depedencies
compile 'com.android.volley:volley:1.0.0'
StringRequest stringRequest;
RequestQueue mRequestQueue;
String url = "http://localhost:5000/bacon"; // This is the localhost to FLask
RequestQueue queue = Volley.newRequestQueue(BaconActivity.this);
stringRequest = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(BaconActivity.this, response, Toast.LENGTH_SHORT).show();
redirectLinkToLogin();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(BaconActivity.this, "That didn't work!", Toast.LENGTH_SHORT).show();
}
}
);
queue.add(stringRequest);
This is the Flask code :
from flask import Flask, request
app = Flask(__name__)
#app.route('/bacon', methods=['GET', 'POST'])
def bacon():
if request.method == 'GET':
return 'You are probably using GET'
else:
return 'You are probably using POST'
if __name__ == "__main__":
app.run(debug=True, host='localhost')
When I run the app, my Volley didn't connect to my Flask (I already run the Flask before running the app). So instead of retrieving the return String, the code runs to the Response.ErrorListener everytime.
I'm trying to get the return String from Flask to the localhost, and Toast the return String.
String url = "http://localhost:5000/bacon"; // This is the localhost to FLask
Actually, no. That's the localhost to the running device. Whether that is the emulator, or your physical Android device.
You may also need Flask to run on host='0.0.0.0'
You need to use the actual IP of your computer running Flask. Android emulator uses 10.0.2.2, I believe
I solved this on my Mac by going to System Preferences > Network and noting my ip.
Then I restarted my dev appserver with this ip address.
dev_appserver.py --host="192.168.1.109" app.yaml
And I used this same ip address in my JsonObjectRequest declaration as well (as part of making a Volley Request.
Now I can use Volley to make GET calls to my local Google Endpoints.

how to create Appoinment from Android MS CRM SDK?

i am creating appointment using below code give "500 Internal Server Error"
i added all fields check it
Appointment objappointment = Appointment.build()
.setSubject("Android sub")
.setDescription("dis from device")
.setRegardingObjectId(new EntityReference("account", UUID.fromString("0717b8e2-d00a-e611-8115-c4346bdd11d1")))
.setOwnerId(new EntityReference("systemuser", UUID.fromString("3edb272d-2da7-4c89-9350-2f4bd4e1762b")))
.setStateCode(new OptionSetValue(0))
.setNew_Latitude(23.7845)
.setNew_Longitude(73.6574)
.setNew_City("Surat")
.setActualStart(mDate.getTime())
.setActualEnd(mDate1.getTime())
.setNew_ZipPostalCode("380060")
.setNew_Street1("Street1")
.setNew_Street2("Street3")
.setNew_street3("Street3")
.setNew_StateProvince("Gujarayt")
.setNew_CountryRegion("India")
.setNew_Latitude(23.7845)
.setNew_Longitude(73.6574)
.setStatusCode(new OptionSetValue(0))
.setPriorityCode(new OptionSetValue(2));
try {
RestOrganizationServiceProxy restService = new RestOrganizationServiceProxy(mOrgService);
restService.Create(objappointment,new Callback<UUID>() {
#Override
public void success(UUID uuid, Response response) {
log("sucess", uuid.toString());
}
#Override
public void failure(RetrofitError error) {
displayError(error.toString());
log("error", error.toString());
}
});
}
catch(Exception ex) {
displayError(ex.getMessage());
log("msg",ex.toString());
}
another entity create successfully using above code just got error in "Appoinment"
Could you get more details of the exception? 500 could be any exception. At least you know the request hit the server and it's failing on the CRM server side. Maybe a plugin or similar is raising the exception.
I think you have to pass the objectid to whom the annotation will be linked to (Account, Contact, or whatever...)
Is that on-premise or online CRM? If OnPremise you could enable includeExceptionDetailInFaults property in the web.config to at least get more details of the exception....

NodeMCU server bad response, when sending GET request from Android app

I've made little server based on NodeMCU. All works good, when I'm conneting from browser, but problem starts, when I'm trying to connect from Android app uisng OkHttp or Volley, I'm receiving exceptions.
java.io.IOException: unexpected end of stream on Connection using OkHttp,
EOFException using Volley.
Problem is very similar for this
EOFException after server responds, but answer didn't found.
ESP server code
srv:listen(80, function(conn)
conn:on("receive", function(conn,payload)
print(payload)
conn:send("<h1> Hello, NodeMCU.</h1>")
end)
conn:on("sent", function(conn) conn:close() end)
end)
Android code
final RequestQueue queue = Volley.newRequestQueue(this);
final String url = "http://10.42.0.17:80";
final StringRequest request = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mTemperatureTextView.setText(response.substring(0, 20));
System.out.println(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error + " + error.toString());
mTemperatureTextView.setText("That didn't work!");
}
}
);
mUpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
queue.add(request);
}
});
What you're sending back is not HTTP. It's nothing but a protocol-agnostic HTML fragment. Furthermore, there's a memory leak lingering.
Try this instead:
srv:listen(80, function(conn)
conn:on("receive", function(sck,payload)
print(payload)
sck:send("HTTP/1.0 200 OK\r\nServer: NodeMCU on ESP8266\r\nContent-Type: text/html\r\n\r\n<h1> Hello, NodeMCU.</h1>")
end)
conn:on("sent", function(sck) sck:close() end)
end)
you need to send back some HTTP headers, HTTP/1.0 200 OK and the newlines are mandatory
each function needs to use it's own copy of the passed socket instance, see how I renamed conn to sck in the two callback functions, see https://stackoverflow.com/a/37379426/131929 for details
For a more complete send example look at net.socket:send() in the docs. That becomes relevant once you start sending more than just a couple of bytes.

Arabic text did not show Json Android when using 3g

when I use this link to get date and day in Arabic language (utf-8)
http://iraqispring.com/apps/get_date_time.php
it is work without problems when I use wifi
but when I use 3g it is get me like this text
الاثنين 2015-01-12
I am using Volley library and this is the code
RequestQueue queuedate = Volley.newRequestQueue(this);
String url ="http://iraqispring.com/apps/get_date_time.php";
StringRequest stringRequestDate = new StringRequest(Request.Method.GET, url,
new Response.Listener() {
#Override
public void onResponse(Object o) {
String dateStr = o.toString();
dateStr.getBytes();
txtDate.setText(dateStr);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context,"not worked 3",Toast.LENGTH_LONG).show();
}
});
what can I do?
While sending such kind of special characters to server you need to encode such input with the help of URLEncoder.encode(your_input, "utf-8") and while receiving such kind of data first of all you need to decode it with the help of URLDecoder.decode(your_data, "utf-8")
I have also faced such kind of problem, so I followed encoding and decoding and resolved the problem.
I think this will help you too.

SIP Stack registration packet with authorization

we want to create SIP application on Android 2.3.3 and have some issues with android.sip stack (default sip stack). Our mobile app sends register sip packet, but
1.) by default OpenIMS core responds 400 Bad request P-Visited-Network-ID Header missing
2.) in the case that we set port number to 4060 -PCSCF /builder.setPort(4060)/ OpenIMS core sends this request from 4060 to 4060 (same port, same IP, same CSCF, same packet) and this is cykling until OpenIMS core send respond to mobile app - 504 Server Time-out.
We also tried SipDemo, CSipSimple and we had same problems.
When we tried Monster Communicator or IMSDroid, then it works!
There is one difference between working and problematic applications - working apps send register packet also with Authorization field.
Part of the code:
public SipManager mSipManager = null;
public SipProfile mSipProfile = null;
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(password);
builder.setDisplayName(username);
builder.setProfileName(username + "#" + domain);
port = Integer.parseInt(4060);
builder.setProtocol(protocol);
mSipProfile = builder.build();
...
try { mSipManager.open(mSipProfile);} catch (SipException e) { ...}
try {
mSipManager.register(mSipProfile, 30, new SipRegistrationListener(){
public void onRegistering(String localProfileUri) {
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
}
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
}
});
} catch (SipException e) {
....
}
How to give authorization field to register packet in classic SIP stack?
We also tried J-SIP but it display error: Conversion to dalvik format failed with error 1.
Every answer would be very appreciated.
Your problem is not related to missing Authorization header.
Registration is done in the following matter:
the client send Register request without "Authorization" header.
server response with 401 response code which includes an header named "WWW-Authnticate", that header hold parameters as realm, opaque, qop and hashing algorithm type.
using these parameters with the username and passord an Authorication header is generated automatically by SIP stacks. and a second Register request is sent which includes the "Authorication" header.
the if the request is send in the correct manner the server return 200 OK response code which means that you are now registered.
Your problem is something else, you don't even get to step 3 (Authorization step), you fail in step 1, for your initial Register request you receive 400 Bad Request response code - which almost always mean that you have a syntax error in your request.

Categories

Resources