HTTP Connection Posting data twice - java

I am writing an application in which I am using Http Connection to post data on a server. My App is working fine when I check it in emulator. My Webservice take too much time to generating responses and my emulator is also responding in a proper way. Somehow when I installed the app on the device, my app is posting data twice on the server. I have checked it... Does anyone have any solution on how to escape from this???
Here I am attaching my code of the sending request. I think the mobile app is sending another request when it reaches HTTP Time out, but I don't know what's the problem. Please Help me.
String param=
"function=OpenRecharge&LoginId="+SharedVariable.getUserInfo().getLoginID()
+"&BatchId="+SharedVariable.getSelectedProduct().getBatchID()
+"&SystemServiceID="+SharedVariable.getSelectedProduct().getSystemServiceID()
+"&ReferalNumber="+strMobileNo
+"&Amount="+strAmount
+"&FromANI="+fromMoNo
+"&Email="
+"&Checksum="+Checksum;
System.out.println("Final Parameter:\n"+param);
connection = (HttpConnection) Connector.open(url);
//Connector.open(param, strAmount, quit)
connection.setRequestMethod(HttpConnection.POST);
connection.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
connection.setRequestProperty("Accept_Language","en-US");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = connection.openOutputStream();
out.write(param.getBytes());
out.flush();
//System.out.println("Status Line Code: " + connection.getResponseCode());
//System.out.println("Status Line Message: " + connection.getResponseMessage());
is=connection.openDataInputStream();
int chr;
StringBuffer sb=new StringBuffer();
while ((chr = is.read()) != -1)
sb.append((char) chr);
System.out.println("Response===>"+sb.toString());

Can you serve up an answer with a place holder text like, "processing..." then after a delay have the web browser try again?

I´m not app developer, anyway your web sevice shouldn´t have a big delay for response. I think this is your problem and you should resolve it. Making a cache or pre-process your response.
Although you can change timeout (it seems fixed), it´s not recommendable beacuse many mobile (wap) proxies have timeout of 30s.

Related

Java Can't Connect To PHP Web Service

Edit:
As I've just seen, it happens even with the simplest setup:
InputStream stream = new URL("http://xx.xx.xxx.xxx/GetAll.php").openStream();
Gives the same timeout error. I think I'm missing some basic configuration.
I used HTTPGet to connect to a PHP web service I have.
I saw it's deprecated so I've been trying to switch to the recommended HttpUrlConnection but with no success.
The HttpURLConnection does not seem to be able connect to the service, even though I can connect from my web browser without any problem.
My connection code:
URL myUrl = new URL("http://xx.xx.xxx.xxx/GetAll.php");
HttpURLConnection request = (HttpURLConnection)myUrl.openConnection();
request.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
InputStream stream = request.getInputStream();
The GetAll.php file:
<?
require_once('MysqliDb.php'); //Helper class
$db = new MysqliDb();
//All closest events by date
$All = $db->query("SELECT * FROM Event;");
//Return in JSON
echo json_encode($All);
The result I am getting from the file:
[{"EventID":1,"StartTime":1300,"Duration":1,"EventDate":"2015-05-17","EventOrder":1,"Type":0,"Name":"\u05e2\u05d1\u05e8\u05d9\u05ea AND ENGLISH","Organiser":"Neta","Phone":"012345678","Location":"Loc","Description":"Desc"}]
Thank you,
Neta
I want to share my solution, as this has cost me hours of hair tearing.
As it turns out, "Timed out" exception has nothing to do with the code, it's a network connectivity issue. The phone I used to debug the app sometimes appears to be connected to Wifi even though it really isn't.
Anyway, if you have this exception, try checking your network connection.
Good luck!

HttpURLConnection slow to disconnect - Java / Android

I want to get the file size of a file on a remote connection without actually downloading the (large) file. I am using the "Content-Length" header of the file. The relevant code is:
URL obj = new URL(FILES_URL + fileName);
String contentLength = "";
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) obj.openConnection();
conn.setConnectTimeout(3000);
conn.setReadTimeout(3000);
contentLength = conn.getHeaderField("Content-Length");
int responseCode = conn.getResponseCode();
Log.d(TAG, "responseCode: " + responseCode);
} finally {
Log.d(TAG, "pre-disconnect");
if (conn!=null) conn.disconnect();
Log.d(TAG, "post-disconnect");
}
return contentLength;
The command "conn.disconnect();" sometimes seems to take forever. I have seen 23 seconds! Admittedly, this is connecting to a secondary local device which is running a web server, but the WiFi signal is strong, relatively fast, and I have never had any such problems using "curl" from my laptop. I do not have control over the web server I am connecting too.
The problem possibly is enhanced when making multiple similar connections to different files one after another, not sure. This is, however, creating entirely new HttpURLConnection's and not reusing the old one. Could reusing the connection help?
I never actually download the file or access the inputstream.
I could just not call disconnect, but I understand it is not recommended because resources would not be released. Is this not correct? I notice URLConnection doesn't have a disconnect. It is just suggested to close any streams you open.
This code is in an asynctask. I guess I could try moving the disconnect call itself to a further asynctask because I don't do anything afterwards. Not sure if that is even possible.
Do you have any suggestions? Should I try something other than HttpURLConnection to get the file size without downloading the file?
Thanks to EJP in the comments. Changing the request method to "HEAD" made the disconnect almost instantaneous:
conn.setRequestMethod("HEAD");
From what I have read, HttpURLConnection.disconnect() will skip through the entire response object if it hasn't been read. Therefore, for very large files, it will take a long time. Using the request method "HEAD" force the response body to be empty and solves the issue.
I suggest you to use either Volley or Okhttp for faster networking but depending on your requirement . Got through Comparison Of Volley And OkHttp and Retrofit and decide which library to use.
As suggestion if you putting this code inside AsyncTask then Read Dark Side of AsyncTask.

HTTPURLConnection Getoutputstream Hanging

I am writing a java code to send POST request to a URL but it is getting hanged on the line indicated by bold. I am running this on android emulator
URL url = new URL("htt
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream urlc = connection.getOutputStream(); //line on which code is getting hanged
OutputStreamWriter writer = new OutputStreamWriter(urlc);
writer.write("message");
writer.close();
I am also able to run internet on emulator browser. That is I have checked that internet is working.
I had the same problem, my mistake was that I set too big timeout(120 seconds).
Bigger timeout makes the HttpUrlConnection to wait more time before consuming each line. When I decreased it to 20 seconds it worked much faster.
before the change - waiting time of 4-5 seconds
after the change - only 0.5-1.5 seconds.
See this is my one of the answer will help you and guide you on right direction.
I had the same problem. You have to enable billing of your application.
If billing is not enabled, the native (HttpURLConnection) in Java 8 environment won't work.
https://cloud.google.com/appengine/docs/standard/java/issue-requests
When your app runs in Java 8 using default behavior, you must enable your application for billing, or you will get the following exceptions:
java.net.UnknownHostException
java.net.SocketTimeoutException
java.io.IOException
The other option is to use the legancy urlfetch, however, then you will encounter additional problems, like this:
Got "DatastoreException: Request is missing required authentication credential" if using Objectify 6.0 and <url-stream-handler> at the same time

Writing to servlet stream

I'm not sure if what I'm trying to do is possible, it might not. Here is my problem:
I'm trying to use a Servlet to pass information from a client to a server via HTTP. This communication is very frequent (I'm passing UI information, so every single mouse event), so I want to have as little overhead as possible to avoid latency issues, which is why I would like to not do a GET call for each transmission. HTTP is a requirement. I'm using an older Tomcat version (Servlet API 2.4). I guess this is somewhat of a web sockets use case, but I don't have any web sockets support available.
What I tried was to open a URL connection on the client side, and to open the input stream (otherwise the doGet() of the servlet never gets called). I'm passing an argument for initialization purposes to the client.
URLConnection uiConnection = url.openConnection();
uiConnection.setRequestProperty("Authorization", "Basic " + encode("xyz" + ":"
+ "xyz"));
uiConnection.setReadTimeout(0);
uiConnection.setDoOutput(true);
uiConnection.setAllowUserInteraction(true);
DataInputStream is = new DataInputStream(
uiConnection.getInputStream());
When I later try to retrieve an ouput stream from this connection, I'm getting a ProtocolException (cannot write output after reading input).
out = new BufferedWriter(new OutputStreamWriter(
uiConnection.getOutputStream()));
out.write(uiUpdate);
On the servlet end I did something like this:
DataInputStream is = new DataInputStream(
request.getInputStream());
Am I completely on the wrong track or is something like this possible without using a new connection for each transmission?
Thanks,
Mark
I think the key question for this, is do you also have http traffic going to this IP? If so, there may not be anything you can do using just java. If not, then create a servlet to listen in on port 80, and parse the incoming data directly.
http://download.oracle.com/javase/tutorial/networking/sockets/clientServer.html

using sockets to fetch a webpage with java

I'd like to fetch a webpage, just fetching the data (not parsing or rendering anything), just catch the data returned after a http request.
I'm trying to do this using the high-level Class Socket of the JavaRuntime Library.
I wonder if this is possible since I'm not at ease figuring out the beneath layer used for this two-point communication or I don't know if the trouble is coming from my own system.
.
Here's what my code is doing:
1) setting the socket.
this.socket = new Socket( "www.example.com", 80 );
2) setting the appropriate streams used for this communication.
this.out = new PrintWriter( socket.getOutputStream(), true);
this.in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
3) requesting the page (and this is where I'm not sure it's alright to do like this).
String query = "";
query += "GET / HTTP/1.1\r\n";
query += "Host: www.example.com\r\n";
...
query += "\r\n";
this.out.print(query);
4) reading the result (nothing in my case).
System.out.print( this.in.readLine() );
5) closing socket and streams.
If you're on a *nix system, look into CURL, which allows you to retrieve information off the internet using the command line. More lightweight than a Java socket connection.
If you want to use Java, and are just retrieving information from a webpage, check out the Java URL library (java.net.URL). Some sample Java code:
URL ur = new URL("www.google.com");
URLConnection conn = ur.openConnection();
InputStream is = conn.getInputStream();
String foo = new Scanner(is).useDelimiter("\\A").next();
System.out.println(foo);
That'll grab the specified URL, grab the data (html in this case) and spit it out to the console. Might have to tweak the delimiter abit, but this will work with most network endpoints sending data.
Your code looks pretty close. Your GET request is probably malformed in some way. Try this: open up a telnet client and connect to a web server. Paste in the GET request as you believe it should work. See if that returns anything. If it doesn't it means there is a problem with the GET request. The easiest thing to do that point would be write a program that listens on a socket (more or less the inverse of what you're doing) and point a web browser to localhost:[correct port] and see what the web browser sends you. Use that as your template for the GET request.
Alternatively you could try and piece it together from the HTTP specification.
I had to add the full URL to the GET parameter. To make it work. Although I see you can specify HOST also if you want.
Socket socket = new Socket("youtube.com",80);
PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket.getOutputStream())));
out.println("GET http://www.youtube.com/yts/img/favicon_48-vflVjB_Qk.png
HTTP/1.0");
out.println();
out.flush();
Yes, it is possible. You just need to figure out the protocol. You are close.
I would create a simple server socket that prints out what it gets in. You can then use your browser to connect to the socket using a url like: http://localhost:8080. Then use your client socket to mimic the HTTP protocol from the browser.
Not sure why you're going lower down than URLConnection - its designed to do what you want to do: http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html.
The Java Tutorial on Sockets even says: "URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the Internet. Sometimes your programs require lower-level network communication, for example, when you want to write a client-server application." Since you're not going lower than HTTP, I'm not sure what the point is of using a Socket.

Categories