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.
Related
I have an MSSQL database and a web api over it.
I can call the api from another pc in the same network with the server ip address, so the IIS Express config allows the connection, the firewall is open and the api is working.
I can call an open weather api from the android app, so my code is working.
But from the android app, when I call my web api, it throws timeout exception.
My client code is:
private async Task<string> FetchWebApiHttpClient(string baseUrl, string path)
{
HttpClient client = new HttpClient();
string result = "";
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
result = await response.Content.ReadAsStringAsync();
}
return result;
}
What can be the problem?
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.
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
Iam sending a POST request from my android app using Xamarin. Iam using HttpClient to make the request
Things I have done:
1) Specified Internet permission
2) Tested the request from Postman for google Chrome
3) Debugged the code step by step
Problem:
1) I get the response as null.
2) Found the issue might be while receiving the response.
Here is my code:-
var resultString = String.Empty;
var registerContent = new StringBuilder();
registerContent.Append("DeviceId=");
registerContent.Append(deviceId);
registerContent.Append("&");
registerContent.Append("Name=");
registerContent.Append(deviceName);
registerContent.Append("&");
registerContent.Append("EncodedAccountNameā€¸=");
registerContent.Append(username);
var client = DataClient.Instance;
var request = new HttpRequestMessage(HttpMethod.Post,new Uri(EndPoints.RegisterDeviceEndPoint, UriKind.Absolute))
{
Content = new StringContent("DeviceId=" + deviceId + "&Name=" + deviceName + "&EncodedAccountName=" + username)
};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var result = await client.SendAsync(request);
if (result.StatusCode == HttpStatusCode.OK)
{
resultString = HostUrl.GeAuthorizationtResult(result.Content.ReadAsStringAsync().Result);
}
return resultString;
Any help is appreciated
Thanks
It looks like you have a lot of app-specific code in there, so it's difficult to say what's causing the issue. You can simplify your code by using HttpClient's built-in support for form posts.
var httpClient = new HttpClient();
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("DeviceId", deviceId),
new KeyValuePair<string, string>("Name", deviceName),
new KeyValuePair<string, string>("EncodedAccountName", username)
};
var response = await httpClient.PostAsync(requestUrl, new FormUrlEncodedContent(values));
response.EnsureSuccessStatusCode();
var resultString = await response.Content.ReadAsStringAsync();
Try this and see if it solves the issue. Otherwise, you'll need to expand on what HostUrl.GeAuthorizationtResult() does.
Let me explain my situation, I developed a complete backend for an Android application in Symfony2.1 that works perfectly, now I'm trying to create the Android app part, for that I created a firewall with http_basic authentication that ensures that my users are correctly authenticated and authorized, I actually can use my app and be logged, but if I try to retrieve any page behind the firewall a get a 404 error.
I don't want to use any external bundle, I just want to send my user/pass on every request since my app makes just three httpclient calls but I don't know hoy to get access granted on every request.
Here is part of my code, feel free to ask :)
Thanks in advance!
My Android http call:
#Override protected String doInBackground(Void... arg0) {
HttpClient httpClient = new DefaultHttpClient();
// construir peticion get
HttpGet httpGet = new HttpGet("http://www.somewebsite.com/api/login/");
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials(loguser, passw), "UTF-8",
false));
try {
response = httpClient.execute(httpGet);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
builder = new StringBuilder();
for(String line = null; (line = reader.readLine()) != null;){
builder.append(line).append("\n");
}
} catch (Exception e) {
e.printStackTrace();
alert("Error de protocolo", "Lo sentimos, ha ocurrido un error");
}
return builder.toString();
}
My firewall
api:
pattern: ^/api/.*
provider: app_user
http_basic:
realm: "API"
access_control:
- { path: ^/api-registro/, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api/.*, role: ROLE_API }
providers:
app_user:
entity: { class: Alood\BackBundle\Entity\Usuario, property: user }
encoders:
Alood\BackBundle\Entity\Usuario: plaintext
My Controller
public function apiLoginAction()
{
$peticion = $this->getRequest();
$sesion = $peticion->getSession();
$usuario = $this->get('security.context')->getToken()->getUser();
$error = $peticion->attributes->get(SecurityContext::AUTHENTICATION_ERROR,
$sesion->get(SecurityContext::AUTHENTICATION_ERROR));
$securityContext = $this->container->get('security.context');
if( $securityContext->isGranted('IS_AUTHENTICATED_FULLY')){
$texto["user"] = $usuario->getUser();
return new JsonResponse($texto);
}
}
Note: If I repeat the same steps in a different function of my controller I get a problem in my android app and I don't know how to solve this.
It happened to be a typo issue in my routing.yml so if its useful for somebody I must say this works properly.