Calling Rest API locally from IOS Xamrin - ios

I am new to xamarin and Rest API.
I am Trying to call Rest API from Xamrine IOS code as follow. My moto is to get List(From API) and Display in list view(Device). But it is giving me error "Bad Request". but when put same URL in POSTMAN , gives me proper response. Please help me out here.
Postman Call Image
Call from Postman
URL: http://localhost/MobileAppAPI/
Client Code:
static List<AuditModel> _audits = new List<AuditModel>();
public static string GetAudits()
{
string URL = "http://localhost/MobileAppAPI/api/Values/Get?id=1000";
string data = CreateObject(URL);
return APIHelper.APIHelper.CreateObject(URL);
}
public static string CreateObject(string URL)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
try
{
using (Stream webStream = request.GetRequestStream())
using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
{
requestWriter.Write("");
}
WebResponse webResponse = request.GetResponse();
using (Stream webStream = webResponse.GetResponseStream())
{
if (webStream != null)
{
using (StreamReader responseReader = new StreamReader(webStream))
{
string response = responseReader.ReadToEnd();
return response;
}
}
}
}
catch (Exception e)
{
Console.Out.WriteLine("-----------------");
Console.Out.WriteLine(e.Message);
return e.Message;
}
return "";
}
API Code:
// GET api/values/5
public string Get(int id)
{
return "value";
}
Exception:
Unhandled Exception:
System.Net.WebException: Error: ConnectFailure (Connection refused)

Related

HttpClient.PostAsync returning Null on A Web API POST

I am trying to get response from an API on few GET and POST calls, whenever i try to get Response from a web API POST it gives an System.NullReferenceException: Object reference not set to an instance of an object.. I am using PostAsync to get response. It works absolutely fine on my local machine but is returning NULL response on deployment machine.
#region API_CALL
System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient();
string CompleteURL = URL.Trim() + URL_FromJSON.Trim();
#region URL Construct For GET Requests
CompleteURL = GetURL(ParameterValue, CallType_FromJSON, CompleteURL);
#endregion URL Construct For GET Requests
string URLContent = string.Empty;
Client.BaseAddress = new System.Uri(CompleteURL);
byte[] cred = UTF8Encoding.UTF8.GetBytes(ClientID.Trim() + Constants.APIConstants.ColonConnector + ClientPass.Trim());
string Encoded = Convert.ToBase64String(cred);
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Constants.APIConstants.AuthTypeBearer, accessToken);
Client.DefaultRequestHeaders.Host = IPAddress.Trim();
CacheControlHeaderValue val = new CacheControlHeaderValue();
val.NoCache = true;
Client.DefaultRequestHeaders.CacheControl = val;
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(Constants.APIConstants.ContentType));
Client.DefaultRequestHeaders.Add(Constants.APIConstants.LicenseKey, LiscenseKEY);
Client.DefaultRequestHeaders.Add(Constants.APIConstants.PostmanToken, PostmanToken);
//client.DefaultRequestHeaders.Add(Constants.APIConstants.AccessToken, accessToken);
System.Net.Http.HttpContent Content = new StringContent(JSONData, UTF8Encoding.UTF8, Constants.APIConstants.ContentType);
// Only for debug purpos:
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Request to API: " + JSONData, Request.ActorID);
HttpResponseMessage Message = new HttpResponseMessage();
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
#region Response Logging
try
{
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Response from API: " + Message.Content.ReadAsStringAsync().Result, Request.ActorID);
}
catch(Exception EX)
{
LogManager.Logger.Invoke(LogLevels.TraceError, Source, "Exception while logging response from API" + EX.ToString()+"Stack: "+EX.StackTrace, Request.ActorID);
}
#endregion Response Logging
if (Message.IsSuccessStatusCode)
{
string Result = Message.Content.ReadAsStringAsync().Result;
ResponseJson = Result;
Description = Result;
}
else
{
try
{
string Result1 = Message.Content.ReadAsStringAsync().Result;
LogManager.Logger.Invoke(LogLevels.TraceInfo, Source, "Failed: ... Recieved JSON: " + Result1, Request.ActorID);
}
catch { }
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
#endregion API_CALL
break;
}
TransactionResponse Response = new TransactionResponse();
Response.Response = ResponseJson;
return Response;
}
catch (Exception Ex)
{
LogManager.ExpLogger.Invoke(Source, Ex, Request.ActorID);
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
the object : Message is null after execution of Message = Client.PostAsync(CompleteURL, Content).Result
Try reading as string asynch with the in the reach of postasynch, use it with the same block of code it works,
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
example:
var = httpresult.content.readasstringasyhnc();
You can also typecast to any model you want her.

Create to database using web api

I am trying to insert a new entry in my database using web api. I have two web projects: one is a UI project where all the user interaction will occur and the other is a services project which will handle all interactions with my database.
Below is my post method that will take in form data for creating a new team.
// POST: Api/Team/Create
[HttpPost]
public ActionResult Create(Team team)
{
try
{
if (ModelState.IsValid)
{
HttpEndPointContext httpEndPoint = new HttpEndPointContext()
{
AuthenticationMethod = HttpAuthenticationMethods.None,
Ssl = false,
HttpMethod = HttpMethod.Post,
Path = "localhost:32173/api/team/",
QueryStrings = null,
PayloadData = SerializationHelper.Current.Serialize(team.ToString(), SerializationTypes.Xml)
};
IProcessResult result = HttpConnectionManager.Current.SendMessage(httpEndPoint);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
And this is my method for dealing with my PayloadStream/PayloadData attribute in the above method:
private void StreamPayload(HttpWebRequest webRequest, HttpEndPointContext httpEndPointContext)
{
if (httpEndPointContext.HttpMethod == new HttpMethod("GET"))
return;
//TODO: FIX MAYBE .... sometimes we want to post body with GET.
//Stream vs string
if (httpEndPointContext.PayloadStream == null)
{
//Wrap with SOAP Envelope and method if defined in SoapDefinition
string data = httpEndPointContext.PayloadData ?? String.Empty;
if (httpEndPointContext.SoapDefinition != null)
{
//If parameters is set, clear existing payload data.
data = String.Empty;
if (httpEndPointContext.SoapDefinition.Parameters != null)
foreach (var parameter in httpEndPointContext.SoapDefinition.Parameters)
{
data += String.Format("<{0}>{1}</{0}>", parameter.Key, parameter.Value);
}
data = String.Format("<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<s:Body><{0} xmlns='{2}'>" +
"{1}</{0}></s:Body></s:Envelope>",
httpEndPointContext.SoapDefinition.SoapMethod, data,httpEndPointContext.SoapDefinition.SoapGlobalKey);
}
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(data);
httpEndPointContext.PayloadStream = new MemoryStream(byteArray);
}
using (Stream requestStream = webRequest.GetRequestStream())
{
StreamHelper.Current.CopyStreams(httpEndPointContext.PayloadStream, requestStream);
requestStream.Close();
}
}
And the code for getting the server response. I'm currently getting an Internal Server (500) Error. Not sure why.
public IProcessResult SendMessage(HttpEndPointContext httpEndPointContext)
{
HttpWebRequest webRequest = CreateWebRequest(httpEndPointContext);
StreamPayload(webRequest, httpEndPointContext);
IProcessResult result = GetWebResponse(webRequest, httpEndPointContext);
return result;
}
private IProcessResult GetWebResponse(HttpWebRequest webRequest, HttpEndPointContext httpEndPointContext)
{
//Get Response
WebResponse response;
IProcessResult result = new ProcessResult(Statuses.Success);
try
{
response = webRequest.GetResponse();
}
catch (System.Net.WebException ex)
{
//Do exception handling. Still get the response for 500s etc.
result.Error.Exception = ex;
result.Status = Constants.Statuses.FailedUnknown;
result.ResponseCodeDescription = ex.Status.ToString();
result.ResponseCode = ex.Status.ToString();
result.Error.ErrorCode = ex.Status.ToString();
response = ex.Response;
//The error did not have any response, such as DNS lookup.
if (response == null)
return result;
}
try
{
//Get the response stream.
Stream responseData = response.GetResponseStream();
if (responseData == null)
throw new CoreException("No Response Data in GetWebResponse.",
"No Response Data in GetWebResponse. EndPoint:{0}", httpEndPointContext.ToString());
// Open the stream using a StreamReader for easy access.
var reader = new StreamReader(responseData);
// Read the content.
result.ResponseData = reader.ReadToEnd();
}
finally
{
response.Close();
}
result.ResponseCode = ((int)((HttpWebResponse)response).StatusCode).ToString();
result.ResponseCodeDescription = ((HttpWebResponse) response).StatusDescription;
return result;
}
And finally, my method for inserting to the database, found in my services project:
//POST api/controller/5
public IProcessResult Insert(Team team)
{
return TeamBusinessManager.Current.Insert(SecurityManager.Current.ConnectionContext, new Team());
}
I'm confused as to why I'm getting the 500 error. I'm not sure if it's the PayloadData attribute in my POST method or is it something wrong with my method in my services project.

An error in Blackberry during HttpConnection message contains Datagram(ConnectionBase).receive (Datagram) line 538

This is my code where the connection problem occuring.
HttpConnection is not getting a response from an connection obj in a input stream. The occuring error is:
Datagram(ConnectionBase).receive (Datagram) line 538
HttpConnection httpCon = null;
InputStream iStream = null;
String url = null;
String result = "";
public GetXmlHttp(String str)
{
url=str;
}
public String RESULT()
{
try
{
httpCon = (HttpConnection)Connector.open(url);
httpCon.setRequestMethod(HttpConnection.GET);
iStream = httpCon.openInputStream();//error is here
int httpResponse = httpCon.getResponseCode();
System.out.println("httpResponse code"+httpResponse);
System.out.println(httpResponse);
if(httpResponse != 200)
return null;
InputStreamReader in = new InputStreamReader(iStream);
StringBuffer sb=new StringBuffer();
char[] ch=new char[1020];
while(in.read(ch)!=-1)
{
sb.append(ch);
}
}
}
Posting the exception would help, but allso have a look at the API documentation for HttpConnection. There is sample code posted there for getting via an HttpConnection which has at least one significant difference from yours. getResponseCode is called before openInputStream:
void getViaHttpConnection(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
int rc;
try {
c = (HttpConnection)Connector.open(url);
// Getting the response code will open the connection,
// send the request, and read the HTTP response headers.
// The headers are stored until requested.
rc = c.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
is = c.openInputStream();

Send POST request for REST api method call

I have a problem with sending POST http request. It stops on (HttpWebResponse)request.GetResponse() and after timeout throws timeout expired exception, but if i send the same request via GET all works fine.
Does any body know what it can be?
try
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
if (content != null)
request.GetRequestStream().Write(content, 0, content.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
return new Response(response);
}
}
catch (WebException exception)
{
return new Response(exception);
}
Most likely, this is due to the code on the server not exposing this method as a POST. If the server doesn't explicitly set anyhting, it defaults to GET only.
Fixed problem with this code:
using (var requestStream = request.GetRequestStream())
{
if (content != null)
{
requestStream.Write(content, 0, content.Length);
}
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return new Response(response);
}
}

Post message from ASP.NET app to Twitter

I am using very simple code to post message in twitter. The code is as given below:
public void UpdateStatus(string username, string password, string tweetMsg)
{
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweetMsg);
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
request.Credentials = new NetworkCredential(username, password);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ServicePoint.Expect100Continue = false;
string statusUpdate = string.Empty;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
statusUpdate = "status=" + System.Web.HttpUtility.UrlEncode(tweetMsg);
sw.Write(statusUpdate);
}
using (HttpWebResponse resp = (HttpWebResponse) request.GetResponse())
{
// Handle response here
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
}
catch (WebException ex)
{
Console.WriteLine("Web Error: {0}", ex.Message);
if (ex.Response != null)
{
HttpWebResponse r = (HttpWebResponse)ex.Response;
using (StreamReader esr = new StreamReader(r.GetResponseStream()))
{
Console.WriteLine("Error: {0}", esr.ReadToEnd());
}
}
}
catch (IOException ex)
{
Console.WriteLine("I/O Error: {0}", ex.Message);
}
}
I am not sure why this code is not working. I am getting the exception
The remote server returned an error: (401) Unauthorized.
But, whichever site I am referring, everywhere I find that people are able to post their messages using the same code.
Can anybody please tell me what I am missing in this code? The site that I referred for this code is http://www.dreamincode.net/forums/topic/120468-twitter-api-posting-status/
Thanks in advance....
Hari
The Twitter API no longer supports Basic Auth for authentication. You need to switch to OAuth which uses tokens instead of passwords.
Twitter's guide to transitioning from Basic Auth to OAuth
OAuth homepage

Resources