What am I doing wrong? My Timeout is not working - android

I have changed the Wi-Fi IP to not be able to connect.
I want that when the 5 seconds pass do something else but it waits about 20 seconds.
URL url = null;
HttpsURLConnection conn = null;
try {
url = new URL("MY_URL");
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("msg", String.valueOf(jsonArray)));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream) conn.getContent(), "UTF-8"));
String response = reader.readLine();

From documentation
Warning: If the hostname resolves to multiple IP addresses, Android's default implementation of HttpURLConnection will try each in RFC 3484 order. If connecting to each of these addresses fails, multiple timeouts will elapse before the connect attempt throws an exception. Host names that support both IPv6 and IPv4 always have at least 2 IP addresses.
That means, if a host has "n" IP addresses involved, it will take n*milliseconds time instead milliseconds you defiend.

Related

do not set cookie with version below Marshmallow

I woluld like to make a raw HTTP GET request in Android setting custom cookie, however the code below works only with android from version 23 and later. With devices and emulators with version below 23 the code does not raise any exception but any cookie is added in the HTTP request (checked server side).
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
CookieHandler test =CookieHandler.getDefault();
HttpCookie lsd=null;
mycoockie= new HttpCookie("myc", coockie);
mycoockie.setDomain(domain);
mycoockie.setPath(path);
mycoockie.setVersion(0);
mycoockie.setMaxAge(-1);
try {
cookieManager.getCookieStore().add(new URI(basicuri), mycoockie);
} catch (URISyntaxException e) {
e.printStackTrace();
}
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
[...]
Thanks for any advice.

How to connect Android to Node.js?

I'm trying to connect Android to Node.js, i have a server running in port 3000 to my localhost, when i try past data from POST method using postman, it works perfectly, but when i do the same with Android whit class HttpUrlConnection this is the result.
Result in the server
this is the code from Node.js
router.post('/', (req, res)=>{
console.log(req.query);
res.send({
mensaje: 'I am from usuario routes'
});
});
and this is from android
URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
//con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.connect();
OutputStream out = new BufferedOutputStream(con.getOutputStream());
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
wrt.append(data);
wrt.flush();
wrt.close();
out.close();
con.disconnect();
You should write the data before connecting to the server:
URL obj = new URL("http://192.168.1.107:3000/");
JSONObject jsonObject = new JSONObject();
jsonObject.put("image", "imagen");
String data = jsonObject.toString();
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(5000);
con.setFixedLengthStreamingMode(data.getBytes().length);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
OutputStream os = con.getOutputStream();
BufferedWriter wrt = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
wrt.append(data);
wrt.flush();
wrt.close();
os.close();
con.connect();
The request in Android is perfect, but in Node i was not using a middleware to convert the body, i used body-parse module and it works.

rest data getting cached android

I am using the code below to fetch data from server. When the data is updated on server, I get the old data from this method. When I use the same method in the web browser i get updated data.
Even when I stop the app and start again it reflects old data but when I have cleaned all my tasks using task manager, I get new data.
Is the data being cached on the device as i am making new request each time
String response = null;
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
if (method == POST) {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(params);
writer.flush();
writer.close();
os.close();
} else {
urlConnection.setRequestMethod("GET");
}
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == HttpURLConnection.HTTP_OK) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
return response;
}
I searched the web and found that use cache is on by default, so these two line might help
urlConnection.setUseCaches(false);
urlConnection.addRequestProperty("Cache-Control", "no-cache");
Append some random parameter i.e. current timestamp to the URL then it will treat as fresh request.
Change This
URL url = new URL(urlString);
To
URL url = new URL(urlString+new Date().getTime());

Communication of Android App with server

I have my android application. I have no idea how to establish communication between the server and the application. I have a login page in the application. I want to send username and password to the server and return yes for valid input and no for invalid input.
Please tell me how to code at server as I have a public ubuntu server but I don't know what to do there in order to establish communication.
Also, what to write at the application code to send data to the server. What will be the URL of the request I have no idea.
Like
I have a public server IP 21.4.3.5 with username : ABC and password : XYZ . Now what will be the URL to send request to the server through the application and to receive the response?
Try this way
URL url = new URL("http://example.sitedemo.service.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Uri.Builder builder = new Uri.Builder().appendQueryParameter("username", "maven")
.appendQueryParameter("password", "123");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");

Why http post on android fails over 3g?

i have an android application that makes an HTTP post request to a server containing some NameValuePairs, and It works just fine over any wifi network, but when i use the same http post over 3g, the server gets a http request with an empty body. Here is the code for the request
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
3);
nameValuePairs.add(new BasicNameValuePair("Name", params[0]));
nameValuePairs.add(new BasicNameValuePair("DNI", params[1]));
nameValuePairs.add(new BasicNameValuePair("Token", params[2]));
URL url = new URL(URL_SERVER);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setReadTimeout(30000);
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(nameValuePairs));
writer.flush();
writer.close();
os.close();
conn.connect();
int responseCode = conn.getResponseCode();
BufferedReader in;
if (responseCode == 404)
in = new BufferedReader(new InputStreamReader(
conn.getErrorStream()));
else
in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Here is the code for the getQuery method
private String getQuery(List<NameValuePair> params)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
Any idea why this happens?
I have new info. I made a form to send the http post over the web browser. that form works great and sends perfectly the body over 3g on Windows phone and over wifi. But when I try to use the chrome of the android phone over 3g to send the http post, it arrives empty, and also if I try to send the http post from one computer connected to a hotspot of my android phone it fails. When i try with the same computer connected to a wifi network, no problem at all. This is so weird. Ideas?
My advice is to use Google's Volley library for networking. It is pretty much the best choice currently when it comes to networking on Android. It really should not be a 3G problem. If it is, you problem might be an isolated one.
Here you have some resources to look at(volley is really easy to use):
https://developers.google.com/events/io/sessions/325304728
https://developer.android.com/training/volley/index.html
Solved, the problem was that the server didn't read properly the requests that had multiple tcp datagrams, and looks like android split the tcp datagrams over 3g

Categories

Resources