I have created my server in amazon ec2 instance. Through my android app i am connecting to the server with HttpUrlConnection. But i get response code as -1. Does anyone has any idea ?? Here is my code.
private String getHttpResponse(final String srcUrl) {
HttpURLConnection urlConnection = null;
FileOutputStream fos = null;
try {
URL url = new URL(srcUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/json");
mETag = readETagFromPrefForCategory();
urlConnection.setRequestProperty("If-None-Match", mETag);
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xyz", "abc".toCharArray());
}
});
urlConnection.connect();
mETag = urlConnection.getHeaderField("ETag");
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
Log.v("http","not modifed");
return readLocalJson();
}
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.w(TAG, "Bad response [" + urlConnection.getResponseCode() + "] from (" + srcUrl + ")");
return null;
}}//end of try block
An answer in this post seemed to solve it for a few people:
Android Https Status code -1
Hope that helps.
The problem might be that your headers HTTP version is not properly formatted. Check this SO link where I have answered a similar question which worked for me.
Java Http~URLConnection response code -1
Why are you setting "Content-Type" on a GET request?
Related
I'm using Google Http Client to code a Post request. Our underlying call is an AJAX post request and the request is successful which return 200 but there is no data added to database. I don't know what wrong with the HTTP Call as the code is design as one HTTP URL call with many function(Add contact, Add organization). How to debug this? Please help me. Thanks.
public void addContact() {
try {
String requestBody = "{'Source': 'Contact', 'MethodName': 'AddContact', 'UserID': '1', 'SalutationID': '1', 'FirstName': 'Peter', "
+ "'LastName': 'Wong', 'JobTitle': 'Software QA', 'PrimaryEmail': 'peterapiit#gmail.com', "
+ "'BusinessPhone': '60163963326', 'CountryID': '104', 'OrganizationID': '1', 'AOIIDs': '2'}";
GenericUrl url = new GenericUrl("https://extranet-uat.who.int/epqs/Main/ServiceProxy");
HttpRequestFactory rf = new NetHttpTransport().createRequestFactory();
HttpRequest request = rf.buildPostRequest(url, ByteArrayContent.fromString("application/json",
requestBody));
request.getHeaders().setContentType("application/json");
HttpResponse response = request.execute();
SoftAssert sAssert = new SoftAssert();
sAssert.assertEquals(response.getStatusCode(), 200);
System.out.println("HTTP Status Code : " + response.getStatusCode());
} catch (IOException ex) {
LogManager.logger.log(Level.INFO, "Exception: " + ex.getMessage());
}
}
The underlying javascript code is available to download from here.
I know there are many different situations that resemble mine across stackoverflow, but I just couldn't make the connection.
What I am trying to do, is to send a simple push notification to the GCM. I found two links for which I try to POST too. Note both these links work in this PHP script i found.
https://gcm-http.googleapis.com/gcm/send
https://android.googleapis.com/gcm/send
I tried to send push notifications from JS to the GCM, but many people have stated that this can not because of security issues. As of now, when I execute my code in Angular JS, I am getting a 405 error from https://gcm-http.googleapis.com/gcm/send. Status 405 means method not accepted (link for reference http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html).
Here is the code for JS. I have two method that I tried.
Method 1:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//ite
}
};
var jsonCall = {
registration_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx-AEQtUUWnCVH566xcwib4HinI16W3_g"
};
xmlhttp.open("POST", "https://gcm-http.googleapis.com/gcm/send", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Authorization", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
xmlhttp.send(jsonCall);
Method 2
var jsonCall = {
registration_id: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx-AEQtUUWnCVH566xcwib4HinI16W3_g"
};
$http({
method:'POST',
url: 'https://gcm-http.googleapis.com/gcm/send',
data: jsonCall,
headers: {
'Authorization': 'A1nxxxxxxxxxxxxxxxxxx',
'Content-type': 'application/json' }
})
This is what I have tried in Java. Note that my project was not created as an Android project, but just as a normal Java project. I get a 411 error here, so I think the string I use as JSON is incorrect. Note that I get a 200 if I use GET.
Method 3:
HttpURLConnection connection = null;
try {
//Create connection
String json ="{\"registration_ids\":[\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxxxx\"]}";
URL url = new URL("https://gcm-http.googleapis.com/gcm/send");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Length", "0");
connection.setRequestProperty("Authorization", "key="+"xxxxxxxxxxxxxxxxxxxxxxxxxx");
System.out.println(connection.getResponseCode());
InputStream stream = (InputStream) connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
//put output stream into a string
BufferedReader br = new BufferedReader(isReader);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
OutputStream os = connection.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.flush();
os.close();
} catch(Exception e){
System.out.println(e);
}
If someone can take a look at this, and set me in the correct direction, I would really appreciate it.
UPDATE:
I have gotten rid of that 411 error. I think it was because I never connected in the first place. Now I am getting the correct 200 code, but the push notification does not send. Is my JSON the correct format?
HttpURLConnection connection = null;
try {
//Create connection
String json ="{\"registration_ids\":[\"APA91bGxHWapgmxgyvPceu85ArDMLaFekbTt5RGzy3gv1xtSO09tJbvnaeVLefBqNl_iBrctoZQ2AltSMfrXykq8-AEQtUUWnCVH566xcwib4HinI16W3_g\"]}";
URL url = new URL("https://gcm-http.googleapis.com/gcm/send");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "key=xxxxxxxxxxxxxxxxxxxxxxx");
connection.connect();
OutputStream os = connection.getOutputStream();
os.write(json.getBytes("UTF-8"));
System.out.println(connection.getResponseCode());
InputStream stream = (InputStream) connection.getInputStream();
InputStreamReader isReader = new InputStreamReader(stream);
//put output stream into a string
BufferedReader br = new BufferedReader(isReader);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
os.flush();
os.close();
} catch(Exception e){
System.out.println(e);
}
This has been solved using the Java method. JS keeps on returning those status codes of 400, 401, 411 etc. It turns out the reason Java returned a 200 but my phone did not receive anything was because my JSON was incorrect. Here is the correct JSON value:
String postData = "{ \"registration_ids\": [ \"" + CLIENT_REG_ID + "\" ], " +
"\"delay_while_idle\": true, " +
"\"data\": {\"tickerText\":\"My Ticket\", " +
"\"contentTitle\":\"My Title\", " +
"\"message\": \"Test GCM message from GCMServer-Android\"}}";
This was obtained from another question I posted, where a fellow SO member provided this solution.
I want to validate an url, whether it exists or throwing page not found error. can anyone help me how to do it in asp.net.
for e.g., my url may be like http://www.stackoverflow.com or www.google.com i.e., it may contain http:// or may not. when i check, it should return the webpage valid if exists or page not found if doesnot exists
i tried HttpWebRequest method but it needs "http://" in the url.
thanks in advance.
protected bool CheckUrlExists(string url)
{
// If the url does not contain Http. Add it.
if (!url.Contains("http://"))
{
url = "http://" + url;
}
try
{
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "HEAD";
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
return false;
}
}
Try this
using System.Net;
////// Checks the file exists or not.
bool FileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if it Exist
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false. So the URL is Not Exist
return false;
}
}
Hope I Helped
Any ideas why on some links that I try to access using HttpWebRequest I am getting "The remote server returned an error: (304) Not Modified." in the code?
The code I'm using is from Jeff's post here (the page seems to have disappeared, see an archive copy at the Wayback Machine).
Note the concept of the code is a simple proxy server, so I'm pointing my browser at this locally running piece of code, which gets my browsers request, and then proxies it on by creating a new HttpWebRequest, as you'll see in the code. It works great for most sites/links, but for some this error comes up. You will see one key bit in the code is where it seems to copy the http header settings from the browser request to it's request out to the site, and it copies in the header attributes. Not sure if the issue is something to do with how it mimics this aspect of the request and then what happens as the result comes back?
case "If-Modified-Since":
request.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]);
break;
I get the issue for example from http://en.wikipedia.org/wiki/Main_Page
PS. UPDATE HERE
Still can't work this out. Basically I can identify 1 link which has an issue, and it seems to work fine, 2nd time it gets the error, 3rd time OK, 4th time gets the error, 5th time OK etc. As if there is some state not getting cleared or something in the code. I've tried to clean up the code a bit using "using" type statements etc.
Here's the code. If anyone can spot why every 2nd time I browse to a link like http://newsimg.bbc.co.uk/css/screen/1_0_16/nol/v4/story.css (starting at the 2nd time, not the first) via this proxy code I get the error I'd love to hear.
class Program
{
static void Main(string[] args)
{
Proxy p = new Proxy(8080);
Thread proxythread = new Thread(new ThreadStart(p.Start));
proxythread.Start();
Console.WriteLine("Proxy Started. Press Any Key To Stop...");
Console.ReadKey();
p.Stop();
}
}
public class Proxy
{
private HttpListener _listener;
private int _port;
public Proxy(int port)
{
int defaultport = 8080;
// Setup Thread Pool
System.Threading.ThreadPool.SetMaxThreads(50, 1000);
System.Threading.ThreadPool.SetMinThreads(50, 50);
// Sanitize Port Number
if (port < 1024 || port > 65535)
port = defaultport;
// Create HttpListener Prefix
string prefix = string.Format("http://*:{0}/", port);
_port = port;
// Create HttpListener
_listener = new HttpListener();
_listener.Prefixes.Add(prefix);
}
public void Start()
{
_listener.Start();
while (true)
{
HttpListenerContext request = null;
try
{
request = _listener.GetContext();
// Statistics (by Greg)
int availThreads = -1;
int compPortThreads = -1;
ThreadPool.GetAvailableThreads(out availThreads, out compPortThreads);
log("INFO", request.Request.Url.ToString(), "START - [" + availThreads + "]");
ThreadPool.QueueUserWorkItem(ProcessRequest, request);
}
catch (HttpListenerException ex)
{
log("ERROR", "NA", "INFO: HttpListenerException - " + ex.Message);
break;
}
catch (InvalidOperationException ex)
{
log("ERROR", "NA", "INFO: InvalidOperationException - " + ex.Message);
break;
}
}
}
public void Stop()
{
_listener.Stop();
}
private void log(string sev, string uri, string message)
{
Console.Out.WriteLine(Process.GetCurrentProcess().Id + " - " + sev + " (" + uri + "): " + message);
}
private void ProcessRequest(object _listenerContext)
{
#region local variables
HttpWebRequest psRequest; // Request to send to remote web server
HttpWebResponse psResponse; // Response from remote web server
List<byte> requestBody = new List<byte>(); // Byte array to hold the request's body
List<byte> responseBody = new List<byte>(); // Byte array to hold the response's body
byte[] buffer;
string uri = "";
#endregion
var listenerContext = (HttpListenerContext)_listenerContext;
uri = listenerContext.Request.Url.ToString().Replace(string.Format(":{0}", _port), "");
// Create Interent Request
HttpWebRequest internetRequest = (HttpWebRequest)WebRequest.Create(uri);
#region Build Request Up
internetRequest.Method = listenerContext.Request.HttpMethod;
internetRequest.ProtocolVersion = listenerContext.Request.ProtocolVersion;
internetRequest.UserAgent = listenerContext.Request.UserAgent;
foreach (string key in listenerContext.Request.Headers.AllKeys)
{
try
{
switch (key)
{
case "Proxy-Connection":
case "Connection":
internetRequest.KeepAlive = (listenerContext.Request.Headers[key].ToLower() == "keep-alive") ? true : false;
break;
case "Content-Length":
internetRequest.ContentLength = listenerContext.Request.ContentLength64;
break;
case "Content-Type":
internetRequest.ContentType = listenerContext.Request.ContentType;
break;
case "Accept":
internetRequest.Accept = listenerContext.Request.Headers[key];
break;
case "Host":
break;
case "Referer":
internetRequest.Referer = listenerContext.Request.Headers[key];
break;
case "If-Modified-Since":
internetRequest.IfModifiedSince = DateTime.Parse(listenerContext.Request.Headers[key]);
break;
default:
internetRequest.Headers.Add(key, listenerContext.Request.Headers[key]);
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Error settup up psRequest object. Error = " + ex.Message + "\n" + ex.StackTrace);
}
}
#endregion
#region Copy content into request
buffer = new byte[1024];
using (Stream instream = listenerContext.Request.InputStream)
{
int incount = instream.Read(buffer, 0, buffer.Length);
while (incount > 0)
{
internetRequest.GetRequestStream().Write(buffer, 0, incount);
incount = instream.Read(buffer, 0, buffer.Length);
}
}
#endregion
// Get Internet Response
HttpWebResponse internetResponse = null;
try
{
using (internetResponse = (HttpWebResponse)internetRequest.GetResponse())
{
#region Configure Local Response Header Keys
foreach (string key in internetResponse.Headers.Keys)
{
try
{
switch (key)
{
case "Transfer-Encoding":
listenerContext.Response.SendChunked = (internetResponse.Headers[key].ToLower() == "chunked") ? true : false;
break;
case "Content-Length":
listenerContext.Response.ContentLength64 = internetResponse.ContentLength;
break;
case "Content-Type":
listenerContext.Response.ContentType = internetResponse.Headers[key];
break;
case "Keep-Alive":
listenerContext.Response.KeepAlive = true;
break;
default:
listenerContext.Response.Headers.Add(key, internetResponse.Headers[key]);
break;
}
}
catch (Exception ex)
{
log("ERROR", uri, "Error settup up listenerContext.Response objects. Error = " + ex.Message + "\n" + ex.StackTrace);
}
}
#endregion
try
{
// Transfer the body data from Internet Response to Internal Response
buffer = new byte[1024];
using (Stream inputStream = internetResponse.GetResponseStream())
{
int outcount = inputStream.Read(buffer, 0, buffer.Length);
while (outcount > 0)
{
listenerContext.Response.OutputStream.Write(buffer, 0, outcount);
outcount = inputStream.Read(buffer, 0, buffer.Length);
}
}
}
catch (Exception ex)
{
log("ERROR", uri, "Could not obtain response from URI: " + ex.Message);
}
finally
{
listenerContext.Response.OutputStream.Close();
}
}
}
catch (Exception ex)
{
//if (ex is InvalidOperationException ||
// ex is ProtocolViolationException ||
// ex is WebException)
//{
// log(uri, "Could not successfully get response: " + ex.GetType() + " - " + ex.Message);
// listenerContext.Response.Close();
// return;
//}
//else { throw; }
log("ERROR", uri, "Could not successfully get response: " + ex.GetType() + " - " + ex.Message);
listenerContext.Response.Close();
}
}
}
And here is an example of what I see - first hit is good, 2nd has error...
Proxy Started. Press Any Key To Stop...
2080 - INFO (http://newsimg.bbc.co.uk:8080/css/screen/1_0_16/nol/v4/story.css): START - [50]
2080 - INFO (http://newsimg.bbc.co.uk:8080/css/screen/1_0_16/nol/v4/story.css): START - [50]
2080 - ERROR (http://newsimg.bbc.co.uk/css/screen/1_0_16/nol/v4/story.css): Could not successfully get response: System.Net.WebException - The remote server returned an error: (304) Not Modified.
First, this is not an error. The 3xx denotes a redirection. The real errors are 4xx (client error) and 5xx (server error).
If a client gets a 304 Not Modified, then it's the client's responsibility to display the resouce in question from its own cache. In general, the proxy shouldn't worry about this. It's just the messenger.
This is intended behavior.
When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.
The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ? at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
It is not an issue it is because of caching...
To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').
After timestamp it should be axios.get(/api/products?${Date.now()}.
It will resolve your 304 status code.
I think you have not installed these features. see below in picture.
I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.
Install Process:
go to android studio
Tools
Android
SDK Manager
Appearance & Behavior
Android SDK
I have 2 pages I created in ASP.net(C#). The first one(called shoppingcart.asp) has a buy it now button. The second one(called processpay.asp) just waits for google checkout to send an HTTP request to it to process the payment. What I would like to do send a post statement to google checkout with a couple of variables that I want passed back to processpay.asp(ie clientid=3&itemid=10), but I don't know how to format the POST HTTP statement or what settings I have to change in google checkout to make it work.
Any ideas would be greatly appreciated.
Google Checkout has sample code and a tutorial on how to integrate it with any .NET application:
Google Checkout API - Google Checkout Sample Code for .NET
Make sure to check the section titled: "Integrating the Sample Code into your Web Application".
However, if you prefer to use a server-side POST, you may want to check the following method which submits an HTTP post and returns the response as a string:
using System.Net;
string HttpPost (string parameters)
{
WebRequest webRequest = WebRequest.Create("http://checkout.google.com/buttons/checkout.gif?merchant_id=1234567890");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{
webRequest.ContentLength = bytes.Length;
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
}
catch (WebException e)
{
// handle e.Message
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{
// get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{
return null;
}
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException e)
{
// handle e.Message
}
return null;
}
Parameters need to be passed in the form: name1=value1&name2=value2
The code will likely end up looking something like this:
GCheckout.Checkout.CheckoutShoppingCartRequest oneCheckoutShoppingCartRequest =
GCheckoutButton1.CreateRequest();
oneCheckoutShoppingCartRequest.MerchantPrivateData = "clientid=3";
GCheckout.Checkout.ShoppingCartItem oneShoppingCartItem =
new GCheckout.Checkout.ShoppingCartItem();
oneShoppingCartItem.Name = "YourProductDisplayName";
oneShoppingCartItem.MerchantItemID = "10";
oneCheckoutShoppingCartRequest.AddItem(oneShoppingCartItem);
Yesterday I used http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx to send the post data and it works fine