Rectangle 27 1

HttpURLConnection
setConnectTimeout()
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);

How to set HttpResponse timeout for Android in Java - Stack Overflow

java android timeout httpresponse
Rectangle 27 54

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

The method write(int) in the type DataOutputStream is not applicable for the arguments (String)

Instead of write(int); I used String str = jsonString.toString(); byte[] data=str.getBytes("UTF-8"); printout.write(data); printout.flush (); printout.close (); It is working.

It's an old answer, but it worked great for me to move away from the deprecated DefaultHttpClient. I also moved from the deprecated NameValuePair to a JSON Object. BTW,I had to change the "write" to "writeBytes".

I was getting the error explained above, wrong parameter types for printout.write(), so I used printout.writeUTF(URLEncoder.encode(params.toString(), "UTF-8"));

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection
Rectangle 27 52

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

The method write(int) in the type DataOutputStream is not applicable for the arguments (String)

Instead of write(int); I used String str = jsonString.toString(); byte[] data=str.getBytes("UTF-8"); printout.write(data); printout.flush (); printout.close (); It is working.

It's an old answer, but it worked great for me to move away from the deprecated DefaultHttpClient. I also moved from the deprecated NameValuePair to a JSON Object. BTW,I had to change the "write" to "writeBytes".

I was getting the error explained above, wrong parameter types for printout.write(), so I used printout.writeUTF(URLEncoder.encode(params.toString(), "UTF-8"));

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection
Rectangle 27 20

I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.

The above example could be written like this:

Webb webb = Webb.create();
webb.post("http://example.com/index.php")
        .param("param1", "a")
        .param("param2", "b")
        .param("param3", "c")
        .ensureSuccess()
        .asVoid();

You can find a list of alternative libraries on the link provided.

I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

Thank you. Downloaded this tiny library and got everything working in less than 15 minutes.

Java - sending HTTP parameters via POST method easily - Stack Overflow

java http post httpurlconnection
Rectangle 27 20

I find HttpURLConnection really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.

The above example could be written like this:

Webb webb = Webb.create();
webb.post("http://example.com/index.php")
        .param("param1", "a")
        .param("param2", "b")
        .param("param3", "c")
        .ensureSuccess()
        .asVoid();

You can find a list of alternative libraries on the link provided.

I'm not going to upvote because your post was less of an answer and more of an advert... but, I played with your library and I like it. Very succinct; lots of syntactical sugar; if you use Java as a bit of a scripting language as I do then it's a great library for very quickly and efficiently adding some http interactions. Zero boilerplate is valuable at times and it may have been useful to the OP.

Thank you, using DefaultHttpClient with https on Android fails with SSLPeerUnverifiedException: No peer certificate (even on correctly signed https certificates), using URL is cumbersome (encoding parameters, checking for result). Using DavidWebb worked for me, thanks.

Thank you. Downloaded this tiny library and got everything working in less than 15 minutes.

Java - sending HTTP parameters via POST method easily - Stack Overflow

java http post httpurlconnection
Rectangle 27 1

Assuming "session file" == "session cookie", perhaps you have not enabled cookie management for HttpUrlConnection. As is described in the documentation, you need to use CookieHandler and CookieManager for this:

CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);

and, new CookieManager() <-- showing up this Error: The constructor CookieManager() is not visible

CookieManager
java.net.CookieManager

@JuHyunLee: If you are using Android 2.2, please switch to using the HttpClient library built into Android (org.apache.http). So long as you reuse the same HttpClient object for each request, session cookies will be maintained for you.

java - Android HttpURLConnection: Why Linux makes session file in ever...

java php android session httpurlconnection
Rectangle 27 270

public class CallAPI extends AsyncTask<String, String, String> {

        public CallAPI(){
            //set context variables if required
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


         @Override
         protected void doInBackground(String... params) {

            String urlString = params[0]; // URL to call

            String data = params[1]; //data to post

            OutputStream out = null;
            try {

                URL url = new URL(urlString);

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                out = new BufferedOutputStream(urlConnection.getOutputStream());

                BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(out, "UTF-8"));

                writer.write(data);

                writer.flush();

                writer.close();

                out.close();

                urlConnection.connect();


            } catch (Exception e) {

                System.out.println(e.getMessage());



            }

        }
    }

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
UTF-8
HttpClient
HttpPost
HttpResponse
HttpEntity
EntityUtils
NameValuePair
BasicNameValuePair
DefaultHttpClient

This does NOT show a POST example. It would be nice to edit the 6.0 answer. This is search engine optimized to show as the first result, which is kind of misleading.

java - Sending POST data in Android - Stack Overflow

java php android client-server httpconnection
Rectangle 27 270

public class CallAPI extends AsyncTask<String, String, String> {

        public CallAPI(){
            //set context variables if required
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


         @Override
         protected void doInBackground(String... params) {

            String urlString = params[0]; // URL to call

            String data = params[1]; //data to post

            OutputStream out = null;
            try {

                URL url = new URL(urlString);

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                out = new BufferedOutputStream(urlConnection.getOutputStream());

                BufferedWriter writer = new BufferedWriter (new OutputStreamWriter(out, "UTF-8"));

                writer.write(data);

                writer.flush();

                writer.close();

                out.close();

                urlConnection.connect();


            } catch (Exception e) {

                System.out.println(e.getMessage());



            }

        }
    }

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
UTF-8
HttpClient
HttpPost
HttpResponse
HttpEntity
EntityUtils
NameValuePair
BasicNameValuePair
DefaultHttpClient

This does NOT show a POST example. It would be nice to edit the 6.0 answer. This is search engine optimized to show as the first result, which is kind of misleading.

java - Sending POST data in Android - Stack Overflow

java php android client-server httpconnection
Rectangle 27 13

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

well i did that but i still get a bad request as a server response.Now let me ask if i did everything corect :When i set the otherparameter should i put param1 or the name of my parameters?also,my json object is the first parameter so first i write this one and after that i write the otherparameters is that right?

On server side the param sequence does not matter.It seems you are puting json in payload ... in this otherParametersUrServiceNeed = "param1=a&param2=b&param3=c"; put the name of parameters that you server need this is just example ..You should first identify the parameters that you server need in request the add these params and there values in String otherParametersUrService as my example demonstrates.

If it is not confidential you can tell me what addition params your server need ..so that i can put them in above example .

Well it's not,it is okay if i give you the method signature??:long InsertStudentAbsences(SRV_Students_Absence objStudentAbsences, string Company, string Lng, string MainPeriod, string UserID, string CourseDate);

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection
Rectangle 27 13

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

well i did that but i still get a bad request as a server response.Now let me ask if i did everything corect :When i set the otherparameter should i put param1 or the name of my parameters?also,my json object is the first parameter so first i write this one and after that i write the otherparameters is that right?

On server side the param sequence does not matter.It seems you are puting json in payload ... in this otherParametersUrServiceNeed = "param1=a&param2=b&param3=c"; put the name of parameters that you server need this is just example ..You should first identify the parameters that you server need in request the add these params and there values in String otherParametersUrService as my example demonstrates.

If it is not confidential you can tell me what addition params your server need ..so that i can put them in above example .

Well it's not,it is okay if i give you the method signature??:long InsertStudentAbsences(SRV_Students_Absence objStudentAbsences, string Company, string Lng, string MainPeriod, string UserID, string CourseDate);

java - Sending a JSON HTTP POST request from Android - Stack Overflow

java android json wcf httpurlconnection
Rectangle 27 90

I don't know if it's the only problem, but you've got a classic Java glitch in there: You're not counting on the fact that read() is always allowed to return fewer bytes than you ask for. Thus, your read could get less than 1024 bytes but your write always writes out exactly 1024 bytes possibly including bytes from the previous loop iteration.

while ( (len1 = in.read(buffer)) > 0 ) {
         f.write(buffer,0, len1);
 }

Perhaps the higher latency networking or smaller packet sizes of 3G on Android are exacerbating the effect?

What a stupid mistake... thanks! This is what happens when you don't read the tutorial properly :)

What about initializing the buffer? What about protecting against exception? What about releasing the resources? I think it is a good but not a complete answer. There are other more complete answers here.

I would like to point out that the > 0 test can prematurely end the reading. The Documentation says that -1 is returned at the end of the stream.

@Clint : true, but the documentation also says (as of java 5), that 0 cannot be returned unless the 'len' param is 0 (If no byte is available (...) -1 is returned; otherwise, at least one byte is read). In java 2, 0 can be returned.

java - Android download binary file problems - Stack Overflow

java android download httpurlconnection fileoutputstream
Rectangle 27 27

I am currently facing the same problem. On 4.1 Jelly Bean I receive an IOException "No authentication challenges found" when calling getResponseCode() on the HttpURLConnection.

As one can see in 4.1 JB the method getAuthorizationCredentials() throws the IOException. It parses the challenge headers it finds in the response using HeaderParser.parseChallenges(..), if the response code is 401 or 407. If the returned List is empty the Exception is thrown.

We are currently investigating what exactly causes that List to be empty, but have the suspicion that our server might use realm=... instead of realm="..." in the challenge header. Missing quotation marks might be the cause for this problem. We have to investigate further if that is indeed the case and if we can make it work.

+1 For a clear explanation and the links to the code. The code also expects realm=" to be the first parameter after the scheme.

By now we have been able to verify that the usage of realm= without quotation marks was indeed the reason which caused this error for us. We were able to change this on our backend side and now everything is working as expected.

I made my app work under android 4.x finally by just removing mHttpConnection.setDoOutput(true);But I still had not knewn clearly about the root cause.

+1 for Excellent response. Problem on my side was the server return of realm=... instead of realm="..." . Fixed that and app started working on both ICS and JB

did you find a workaround for this? It works on kitkat, but not on JB

HttpURLConnection worked fine in Android 2.x but NOT in 4.1: No authen...

android authentication httpurlconnection
Rectangle 27 11

I just figured out that HttpURLConnection adds Content-Type header with value application/x-www-form-urlencoded by itself. I've done it using HTTP sniffer on my android emulator.

This auto-added header caused signature mismatch. After I changed the code on the server-side to allow requests with Content-Type: application/x-www-form-urlencoded it generates the right signature and it works fine.

java - HttpURLConnection PUT to Google Cloud Storage giving error 403 ...

java android google-cloud-storage httpurlconnection put
Rectangle 27 25

The 401 (Unauthorized) response message is used by an origin server to challenge the authorization of a user agent. This response MUST include a WWW-Authenticate header field containing at least one challenge applicable to the requested resource.

java.io.IOException: No authentication challenges found
401 Unauthorized
407 Proxy Authentication Required

If you own the server-side API, then you can fix it by adding the required WWW-Authenticate header when you return 401 or 407. In my case, I fixed it in PHP as follows:

header('WWW-Authenticate: OAuth realm="users"');
header('HTTP/1.1 401 Unauthorized');

HttpURLConnection worked fine in Android 2.x but NOT in 4.1: No authen...

android authentication httpurlconnection
Rectangle 27 5

Probably you are trying to perform network operation on UI thread, which Android 3.0+ devices won't allow. They will throw an exception indicating that you are performing network operation on UI thread.

AsyncTask
Thread

java - HttpUrlConnection getOutputStream throws IOException - Stack Ov...

java android httpurlconnection ioexception
Rectangle 27 3

There's a difference between your HTTP traffic for iOS and for Android. This is guaranteed, otherwise you'd get identical behaviour from the server. The difference is probably in HTTP header(s) &/or parameter(s).

This is very difficult to debug remotely via SO Q&A - E.g. we don't know what headers & parameters your iOS client is successfully using nor how your server is configured & programmed.

  • Compare (2) and (3). For the most thorough comparison, save each HTTP request and response message as a separate file for (2) and (3), then diff the corresponding files.

Seems you have the same problem for both GET and POST: the server is configured for BASIC authentication, but the client is not following the authentication protocol correctly. I think it just shows as a slightly different sympton in the two cases: for GET it says 'resource not found' (because you're not authenticated) and for POST the resource is given by you, but the server says you're not authorized to change the resource on the server. I suggest you've done enough (good!) debugging of request contents and now you should stop and focus on getting authentication working.

Authorization
WWW-Authenticate
WWW-Authenticate: Basic realm="Protected"
  • Now send an additional GET request to server that (either without/with the original request contents), but includes the Authentication header, with Base 64 encoded username:password (Authorization: Basic ZnJhbms6ZmllZGxlcg==)

Good work. Thanks. :-) Did you see a response message with Burp?

I am able to look at response. It always times out with coe 408. Yesterday also when using proxy server I was having this problem. If I turn proxy server off then I never get timeout and get exception as described in my question.

When you see the Request message displayed, then on the Interception tab click Forward. This sends the Request to the server, which returns the Response, which should then be displayed by Burp.

java - HttpUrlConnection not working and shows different status code f...

java android exception authentication httpurlconnection
Rectangle 27 23

Its' taken me a few hours but I managed to build a custom cookie storage myself.

You have to attach this by doing this:

public class application extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
       CookieManager cmrCookieMan = new CookieManager(new MyCookieStore(this.objContext), CookiePolicy.ACCEPT_ALL);
       CookieHandler.setDefault(cmrCookieMan);
       }
    }
/*
 * This is a custom cookie storage for the application. This
 * will store all the cookies to the shared preferences so that it persists
 * across application restarts.
 */
class MyCookieStore implements CookieStore {

    /*
     * The memory storage of the cookies
     */
    private Map<URI, List<HttpCookie>> mapCookies = new HashMap<URI, List<HttpCookie>>();
    /*
     * The instance of the shared preferences
     */
    private final SharedPreferences spePreferences;

    /*
     * @see java.net.CookieStore#add(java.net.URI, java.net.HttpCookie)
     */
    public void add(URI uri, HttpCookie cookie) {

        System.out.println("add");
        System.out.println(cookie.toString());

        List<HttpCookie> cookies = mapCookies.get(uri);
        if (cookies == null) {
            cookies = new ArrayList<HttpCookie>();
            mapCookies.put(uri, cookies);
        }
        cookies.add(cookie);

        Editor ediWriter = spePreferences.edit();
        HashSet<String> setCookies = new HashSet<String>();
        setCookies.add(cookie.toString());
        ediWriter.putStringSet(uri.toString(), spePreferences.getStringSet(uri.toString(), setCookies));
        ediWriter.commit();

    }

   /*
    * Constructor
    * 
    * @param  ctxContext the context of the Activity
    */
    @SuppressWarnings("unchecked")
    public MyCookieStore(Context ctxContext) {

        spePreferences = ctxContext.getSharedPreferences("CookiePrefsFile", 0);
        Map<String, ?> prefsMap = spePreferences.getAll();

        for(Map.Entry<String, ?> entry : prefsMap.entrySet()) {

            for (String strCookie : (HashSet<String>) entry.getValue()) {

                if (!mapCookies.containsKey(entry.getKey())) {

                    List<HttpCookie> lstCookies = new ArrayList<HttpCookie>();
                    lstCookies.addAll(HttpCookie.parse(strCookie));

                    try {

                        mapCookies.put(new URI(entry.getKey()), lstCookies);

                    } catch (URISyntaxException e) {

                        e.printStackTrace();

                    }

                } else {

                    List<HttpCookie> lstCookies = mapCookies.get(entry.getKey());
                    lstCookies.addAll(HttpCookie.parse(strCookie));

                    try {

                        mapCookies.put(new URI(entry.getKey()), lstCookies);

                    } catch (URISyntaxException e) {

                        e.printStackTrace();

                    }

                }

                System.out.println(entry.getKey() + ": " + strCookie);

            }

        }

    }

    /*
     * @see java.net.CookieStore#get(java.net.URI)
     */
    public List<HttpCookie> get(URI uri) {

        List<HttpCookie> lstCookies = mapCookies.get(uri);

        if (lstCookies == null)
            mapCookies.put(uri, new ArrayList<HttpCookie>());

        return mapCookies.get(uri);

    }

    /*
     * @see java.net.CookieStore#removeAll()
     */
    public boolean removeAll() {

        mapCookies.clear();
        return true;

    }        

    /*
     * @see java.net.CookieStore#getCookies()
     */
    public List<HttpCookie> getCookies() {

        Collection<List<HttpCookie>> values = mapCookies.values();

        List<HttpCookie> result = new ArrayList<HttpCookie>();
        for (List<HttpCookie> value : values) {                
            result.addAll(value);                
        }

        return result;

    }

    /*
     * @see java.net.CookieStore#getURIs()
     */
    public List<URI> getURIs() {

        Set<URI> keys = mapCookies.keySet();
        return new ArrayList<URI>(keys);

    }

    /*
     * @see java.net.CookieStore#remove(java.net.URI, java.net.HttpCookie)
     */
    public boolean remove(URI uri, HttpCookie cookie) {

        List<HttpCookie> lstCookies = mapCookies.get(uri);

        if (lstCookies == null)
            return false;

        return lstCookies.remove(cookie);

    }

}

This hasn't been thoroughly tested but I'll make edits as I go along. Please suggest improvements.

Sometimes I wonder if I am crazy to expect something as fundamental as persistent cookies to be included in the SDK... I'll be sure to post back if I can suggest any improvements.

with this implementation, it will add cookies to the exact URI from which they came, meaning they will not be sent to any other URIs at that host. I recommend replacing the passed URI with a new URI consisting of just the host name in order to make this behave as expected. ex: with the current implementation, if you visit yourdomain.com/pageOne.htm, any cookies set will not be sent when you visit yourdomain.com/pageTwo.htm since the URIs are different. the implementation should trim the URI parameter down to just yourdomain.com in order for it to behave as (I) expected.

Cookies are not sync-ed to SharedPreferences on each delete, add or update. This way, when the app is killed and then it is restarted, the cookie store just created will be the same as the one before the app was killed.

I found the fatal problem in this approach. HttpCookie.toString() does not produce a string which can be parsed again with HttpCookie.parse(). toString() omits the Version parameter as it is designed to be sent in the Cookie: header. If parse() sees no Version parameter, it ignores the rest of the parameters, because it is designed to parse the Set-Cookie/Set-Cookie2 headers. It's tragic that whoever wrote this API made so many mistakes (making cookies non-serialisable, not providing a way to format a cookie for the other header, making the only way of setting it a static method, etc., etc.)

java - How do I persist cookies when using HTTPUrlConnection? - Stack ...

java android cookies httpurlconnection
Rectangle 27 28

new DefaultHttpClient().execute(new HttpGet("http://www.path.to/a.mp4?video"))
        .getEntity().writeTo(
                new FileOutputStream(new File(root,"Video.mp4")));

I like one line solution as well. However, you should check entity before writing to file, otherwise the file will be created even if there is a problem with download. So next time, you might attempt to open a damaged file.

How do I name the downloaded file same as the original file name dynamically?

With that method, you'd need to add a few things, such as getting the Content-Disposition header that contains the file name.

Awesome .. (+1).. this works reli well..and the pdf downloaded is never corrupted also..

java - Android download binary file problems - Stack Overflow

java android download httpurlconnection fileoutputstream
Rectangle 27 24

  • Once you have authenticated the user and stored the session_id locally, send the session_id in the header of each of your http requests. That way, you're not sending the credentials with each request, but the session id. And if something happens on the server side to the session, the transaction will not be allowed.
  • When logging out, don't just delete the session_id on your app (client) side. Send a logout to the server as well so that the session can be killed server side.
  • If the session is killed on the server side, you'll want to do 1 of 2 things A) prompt the user to re-login. B) Use the store credentials to log back in, create a new session id and store it again in your singleton.

I don't think he is making any more http requests other than the initial login one. Most of his functionality seems local. +1 for mentioning the correct way to do authenticated requests.

java - Android App Strategy for keeping track of a login session - Sta...

java android session login httpurlconnection
Rectangle 27 24

  • Once you have authenticated the user and stored the session_id locally, send the session_id in the header of each of your http requests. That way, you're not sending the credentials with each request, but the session id. And if something happens on the server side to the session, the transaction will not be allowed.
  • When logging out, don't just delete the session_id on your app (client) side. Send a logout to the server as well so that the session can be killed server side.
  • If the session is killed on the server side, you'll want to do 1 of 2 things A) prompt the user to re-login. B) Use the store credentials to log back in, create a new session id and store it again in your singleton.

I don't think he is making any more http requests other than the initial login one. Most of his functionality seems local. +1 for mentioning the correct way to do authenticated requests.

java - Android App Strategy for keeping track of a login session - Sta...

java android session login httpurlconnection