I am trying to set up an http post in my Blackberry app. I have successfully implemented this in my corresponding Android app, so I know the server it working find. I have tried several different things, and I'm not really getting errors, its just the info on the server is not getting updated. I have looked at this post:
Http POST in BlackBerry, and several others. I found them helpful, but they didn't ultimately solve my problem. Again, I don't get errors, but the server doesn't get updated. Here is the code I am currently using:
String url = "http://xxxx.com/ratings/add?;deviceside=true";
String postStr1 = "business_id=790";
String postStr2 = "&rating=4";
HttpConnection httpConnection = (HttpConnection) Connector.open(url);
httpConnection.setRequestMethod(HttpConnection.POST);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("business_id", String.valueOf(790));
encPostData.append("rating", String.valueOf(4));
byte[] postData = encPostData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postData.length));
OutputStream os = httpConnection.openOutputStream();
os.write(postData);
os.flush();
Anyone have any ideas on what could be wrong?
A few things were going on. First, my simulator was not connecting to the internet properly. Once that got straightened out, I removed the
deviceside=true
from my url, and it now works great. Thanks all!
Related
I have been working on this problem for quite some time. I've read the many similar posts and their solutions don't help me (many posts are old and stale). I have a new Xamarin project and a localhost API that I am testing to. Initially I installed our production API locally and it doesn't connect. So I created a smaller test API and have had varying results in connecting. Xamarin Android will not connect with a "Failed to connect to localhost:XXXXX" message. I built a WPF project and get the same results. However I can connect to outside public API's (github) with both. I can connect to my localhost with a Windows forms desktop app and successfully get & post. Postman and httprepl both connect locally and successfully get & post. A couple of the other things the other posts suggested are 1) Client handler to ignore SSL - doesn't work, 2) Use the emulator's browser to connect to localhost - cannot connect. (this might be exposing where the problem really is but not sure).
Also The debugger seems to be behaving oddly. When the debugger gets to the HttpResponseMessageresponse.... line it rarely makes it to the next line so I cannot inspect the statuscode. The block I have below is in a try/catch and rarely makes it to the catch if the connection truly fails. Sometimes it will be caught at the catch and that's how I get the "failed to connect" message. Another developer here has run the project on his computer and gets the same results/errors on his computer.
HttpResponseMessage response = await client.SendAsync(request);
var Statuscode = response.StatusCode;
if (response.IsSuccessStatusCode)
{
var jsonbody = response.Content.ReadAsStringAsync().Result;
var ResponseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
}
else
{
string oops = "Nothing";
}
I seem to be running out of options and am looking for any advice.
Thanks in advance.
Last time we tested our application was on Tuesday, it was working well.
Today morning a long wait and timeout received from Microsoft when sending DETECT request with binary data in body. Nothing has changed between in our application.
I tested and my keys are okay (when they are not, we receive an answer but not 200, not a timeout).
When I try to DETECT using an URL, it is working (proper content-type and body of course)
Did anyone noticed the same, or using the API differently?
HttpClient client = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("https://westeurope.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceLandmarks=false&returnFaceId=true");
request.addHeader("Ocp-Apim-Subscription-Key", MY_KEY);
request.addHeader("Content-Type", "application/octet-stream");
HttpEntity entity = new ByteArrayEntity(Base64.getDecoder().decode(base64));
request.setEntity(entity);
response = client.execute(request);
It seems it was not a problem at out side. Suddenly it started to work...Hopefully will stay this way.
I am using the following code....
Dim myHttpWebRequest As HttpWebRequest = CType(WebRequest.Create(PostingUrl), HttpWebRequest)
myHttpWebRequest.Method = "POST"
myHttpWebRequest.Headers.Add("Authorization", "Bearer " & RSettings.access_token)
myHttpWebRequest.Headers.Add("Accept-Version", "2")
myHttpWebRequest.ContentType = "application/json; charset=UTF-8"
myHttpWebRequest.Accept = "application/json"
' myHttpWebRequest.Proxy = Nothing ' ** SEE NOTES ON THIS LINE **
Dim Byt As Byte() = Encoding.UTF8.GetBytes(DataString)
Using stream = myHttpWebRequest.GetRequestStream()
stream.Write(Byt, 0, Byt.Length)
End Using
Using myHttpWebResponse As HttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Using srRead As New StreamReader(myHttpWebResponse.GetResponseStream())
ListingResponse = srRead.ReadToEnd()
End Using
End Using
Where:
PostingUrl is "https://reverb.com/api/listings"
RSettings.access_token is (obviously) my access token for this API
DataString is a JSON string posting the data to the Reverb API
If I run my code from Visual Studio (localhost) it returns
The remote server returned an error: (406) Not Acceptable.
Trying to figure out why, I opened Fiddler hoping I could inspect content types and figure out the problem, but the response error changed to:
The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
(I'm guessing from this error that I also have an issue with my Auth key, but that's a separate subject I think.)
After a bit of Googling and S/O pages I found two suggestions:
Tools > Fiddler Options > HTTPS and uncheck "Capture HTTPS CONNECTs"
Add the commented out line: myHttpWebRequest.Proxy = Nothing
If I make any of those changes, I get back to my Error 406 that I get without Fiddler running.
However, if I add myHttpWebRequest.Proxy = Nothing line added, I can no longer see the Tunnel to http://reverb.com:443 Log entry in Fiddler, there's no record of a request to Reverb.com so I can't inspect anything.
I'm now very confused about what I'm doing, and I guess haven't actually made any progress at all!
I still have error 406 and don't seem to be able to inspect the headers/content type issues with Fiddler as I had hoped (please explain how if I am wrong!)
Even if I do correct the 406, I think I have an authentication error.
By the way... all this is an attempt to recreate the cURL example on the Rever docs page here:
https://dev.reverb.com/docs/create-a-listing
I have also been discussing this issue here:
https://dev.reverb.com/v1.0/discuss/57bb2ca0aa8f760e004588cf
Argh... well, my confusing over Fiddler still stands but the 406 error was caused by this:
myHttpWebRequest.Headers.Add("Accept-Version", "2")
Should have been
myHttpWebRequest.Headers.Add("Accept-Version", "2.0")
How simple!!
Please, someone help me. I've been researching this for hours, have tried lots of different suggested fixes, and I'm at a total loss as to why I am still getting this error.
I have an ASP.NET 4.0 web page with the following code in it:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetHref);
// request.KeepAlive = false;
// request.ProtocolVersion = System.Net.HttpVersion.Version10;
// request.ServicePoint.Expect100Continue = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
I've tried every combination I can imagine of un-commenting the above 3 commented lines.
I have this in my web.config:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing ="true"/>
</settings>
</system.net>
When I am running Fiddler on my dev machine, the page runs without exception and fiddler shows this message at the top of the return:
HTTP/1.0 200 This buggy server did not return headers
Without Fiddler running, I get the error every time on the request.GetResponse() line.
Well, I tried every suggestion I could find here on StackOverflow and elsewhere on the web, but never got an implementation of HttpWebRequest to work for me, so I tried using TcpClient instead after reading this:
How To Set useUnsafeHeaderParsing For .NET Compact Framework
To get it to work for me, I had to modify this line:
sw.WriteLine(string.Format("GET /{0} HTTP/1.1", pathAndQueryString));
to:
sw.WriteLine(string.Format("GET /{0} {1}", pathAndQueryString, Environment.NewLine+Environment.NewLine));
And that worked.
In asp.net with C# this issue is associated with port only.
Many programs use 80 port thats why you get this error, so get rid of this issue no configuration is required just close your
Skype, VPN softwares etc.. and it will resolve your issue.
In my case actually it was not Skype but hotspot shield (a free VPN) software was running in background quitting that software resolved my issue.
I have an Android application with an ASP.NET backend. I have the registration_id for the phone as well as an auth token from google for the application server that is performing a push.
When I make the http post request to C2DM so that the phone gets a message I keep getting the 401 Unauthorized. Here is how I'm making the request in .NET:
WebRequest myRequest = WebRequest.Create("https://android.apis.google.com/c2dm/send");
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.Method = "POST";
myRequest.Headers.Add("Authorization", "GoogleLogin auth=" + authId);
// buiold the post string
StringBuilder myPost = new StringBuilder();
myPost.AppendFormat("registration_id={0}", regId);
myPost.AppendFormat("&data.payload={0}", msg);
myPost.AppendFormat("&collapse_key={0}", colKey);
// write the post-string as a byte array
byte[] myData = ASCIIEncoding.ASCII.GetBytes(myPost.ToString());
myRequest.ContentLength = myData.Length;
Stream myStream = myRequest.GetRequestStream();
myStream.Write(myData, 0, myData.Length);
myStream.Close();
// Do the actual request and read the response stream
WebResponse myResponse = myRequest.GetResponse();
Stream myResponseStream = myResponse.GetResponseStream();
StreamReader myResponseReader = new StreamReader(myResponseStream);
string strResponse = myResponseReader.ReadToEnd();
myResponseReader.Close();
myResponseStream.Close();
Any help would be much appreciated.
Advice corner: Have some confidence in your code every once and a while! And, even Google messes up sometimes.
After spending about nine hours reading every blog post and article about Google OAuth and C2DM and trying different things in my code, I emailed Google. I'm excited to say that not only did I receive a response very quickly, but also that my account was messed up. Something went wrong while I was registering on their site and although it appeared that everything was working from the registration success email I received, it wasn't. I re-registered and everything works!
I have encountered a similar problem: error 401 "Unauthorized" while trying a google c2dm (cloud to device messaging) code sample. It looks like the example used to work as is, but now Google has changed its conditions. Before running code examples, you have to sign-up:
http://code.google.com/android/c2dm/signup.html
I signed up, and the stuff began to work in minutes.
I've got the same problem, i.e. suddenly my C2DM_ACCOUNT_EMAIL stopped working.
To solve the problem, just fill the registration again with same info and the same C2DM_ACCOUNT_EMAIL.
HTH