HttpUrlConnection getResponseCode throws IOException - android

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:

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.

Android HttpUrlConnection erroor handling

I'm developing an Android app which works with server. I have POST request (using HttpURLConnection). Code is:
//setting URL to HttpURLConnection conn
conn.setReadTimeout(30000);
conn.setConnectTimeout(14000);
conn.setChunkedStreamingMode(0);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder();
for (Map.Entry<String, String> entry : paramList.entrySet())
builder.appendQueryParameter(entry.getKey(), entry.getValue());
String query = builder.build().getEncodedQuery();
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
responseCode = conn.getResponseCode(); // IOException!
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
In case of error I need to show exact error message, for instance, "Connection timeout", or "Read timeout", or "Authorization problems" (for 401 status), etc.
How can I handle:
Connection timeout?
ReadTimeout?
And how can I get response code if it throws an IOException if server responses 4xx status? I read several questions here, but I didn't understand, how can I handle timeout errors and how can I get response code in case of IOException.

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());

Android HttpURLConnection set GET Request method

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

POST function for REST service returns empty response

I'm trying to do a post method for a REST service, but I'm not getting any response from server:
public JSONObject postValues (String strUrl, String strJsonArray) throws Exception{
JSONObject jsonObject = null;
URL url = new URL(strUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
strJsonArray = "data=" + strJsonArray;
Log.e("result",""+strJsonArray);
OutputStream os = conn.getOutputStream();
os.write(strJsonArray.getBytes());
os.flush();
conn.connect();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
StringBuilder sb = new StringBuilder();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
Log.e("output",output);
sb.append(output);
}
Log.e("output",sb.toString());
jsonObject = new JSONObject(sb.toString());
conn.disconnect();
return jsonObject;
}
When I see my logCat a get:
output {}
I know that the server is working right because I'm using the "advanced REST client" plugin of google chrome. If I call the URL manually (using the plugin of course)I get the desired answer:
{"message":"OK","code":200}
But if I try to use my function, my strJsonArray is inserted but I get an empty respond from server.
Is there anything wrong with my code?.
Everything looks good...
You could use Wireshark to capture the packets sent to and received from the server using an emulator and the chrome rest client. Then you can compare them and maybe find out what's wrong.
You could also check if theres something in the error stream (conn.getErrorStream()).

Categories

Resources