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.
Related
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.
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());
I would like to send HTTP Request with GET method, but I can't set the GET method.
Here's my code:
try {
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("p1", "123")
.appendQueryParameter("p2", "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();
Log.e("ERROR", conn.getResponseMessage());
Log.e("ERROR", conn.getRequestMethod());
Log.e("ERROR", String.valueOf(conn.getResponseCode()));
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
In the code, I set GET method, but on the log, request method is POST:
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ Method Not Allowed
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ POST
02-01 16:48:54.766 23799-23831/? E/ERROR﹕ 405
What is a problem?
the problem is
conn.setDoOutput(true);
when set to true the request method is changed to POST, since GET or DELETE can't have a request body
I am using HttpURLConnection class to send Post request to my server but its not working, I did the same Post call using DefaultHttpClient & its work properly, but in android org.apache.http.impl.client.DefaultHttpClient is deprecated, that's why I am using HttpURLConnection class. I don't know is anything wrong with the way I am sending the JSON object or something else.
Below is my code implementation
URL url = new URL(linkPath);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
writer.close();
out.close();
urlConnection.disconnect();
I got IOException when i try call getCodeResponse(). When parameters are valid there is no exception and code response is 200. In case of wrong parameteres server should return 401 code. I've tested query on hurl.it and in case of wrong parameters i got 401 code. Maybe HttpURLConnection class throws exception when error code occurs.
URL url = new URL(sUrl);
String charset = "UTF-8";
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(DEFAULT_TIMEOUT /* milliseconds */);
conn.setConnectTimeout(DEFAULT_TIMEOUT /* milliseconds */);
conn.setRequestMethod(methodType);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("Accept-Charset", charset);
conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.addRequestProperty(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os));
writer.write(query);
writer.flush();
writer.close();
//os.write(query.getBytes());
os.flush();
os.close();
conn.connect();
if(conn != null){
responseCode = conn.getResponseCode();
result = readResponse(conn);
}
The IOException means that there is a 401 response. Print the stacktrace and if everything else is correct, it'll give a 401 response. Something like : java.io.IOException: Server returned HTTP response code: 401 for URL: