-3

In one of my android app, i am getting error "java.net.ProtocolException: Connection already established" during call the API. (I refered "Connection already established" exception in HttpsURLConnection for solution but not useful)

Below is my code to call API. Code is working for all the API except the one. That API is the same way developed as the Others and still below code throwing error for that API.

HttpURLConnection con = null;
                BufferedReader in = null;
                StringBuilder sb = new StringBuilder();
                try {

                    URL uri = null;
                    uri = new URL(url);
                    LogUtil.v("~~URL - "+url);

                    con = (HttpURLConnection) uri.openConnection();
                    System.setProperty("http.keepAlive", "false");
                    con.setRequestMethod(requestType); //type: POST, PUT, DELETE, GET
                    con.setDoOutput(true);
//                  con.setDoInput(true);
                    con.setConnectTimeout(TIMEOUT); //20 secs
                    con.setReadTimeout(TIMEOUT); //20 secs
                    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                    String authorizationString = "Basic " + Base64.encodeToString((myAuthString).getBytes(), Base64.DEFAULT); 

                    con.setRequestProperty("Authorization", authorizationString);

                    if( body != null){

                        LogUtil.v("~~BODY - "+body);

                        DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                        out.writeBytes(body);
                        out.flush();
                        out.close();
                    }

                    con.connect();
                    InputStream inst = con.getInputStream();
                    in = new BufferedReader(new InputStreamReader(inst));

                    String temp = null;

                    while((temp = in.readLine()) != null){
                        sb.append(temp).append(" ");
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    if(in!=null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(cb!=null){
                        if (sb.toString().length() >0) {
                            LogUtil.v("~~ RESPONSE - "+ sb.toString());
                            cb.onResponse(sb.toString(), actionCode);
                        }else{
                            LogUtil.v("~~ RESPONSE - null");
                            cb.onResponse(null, actionCode);
                        }
                    }
                                    if(con!=null)
                                            con.disconnect();

                }

Please don't suggest to use DefaultHttpClient here.

I want to solve the problem using above BECAUSE IT IS WORKING FOR ALL OTHER APIS.

FYI: API CALL IS ALREADY CHECKED USING BROWSER AND IT IS RETURNING RETURNING DATA. IT IS JUST THROWING ERROR WHEN CALLING FROM ANDROID.

~~~~~~ EDITED ~~~~~~~~~ (SERVER SIDE APIS ARE DEVELOPED IN PHP)

Let me simplify my problem explanation:

function API1Call(){
   // callAPI(param...)
}

function API2Call(){
   // callAPI(param...)
}

callAPI(param..){

// above API call code goes here
}

if you see the function callAPI(param...), it executing whenever required to call API.

***> Now in my proj, i m calling many apis written on different activites.

Only for One API call, above callAPI(param...) throwing exception that i mentioned above.***

~~~~~ MY LOGCAT ~~~~~~~

08-31 14:22:45.309: W/System.err(27364): java.net.ProtocolException: Connection already established
08-31 14:22:45.314: W/System.err(27364):    at java.net.HttpURLConnection.setRequestMethod(HttpURLConnection.java:666)
08-31 14:22:45.324: W/System.err(27364):    at libcore.net.http.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java:144)
08-31 14:22:45.329: W/System.err(27364):    at 
com.indapoint.ewe.api.EWeAPI$1.run(EWeAPI.java:245)
08-31 14:22:45.334: W/System.err(27364):    at java.lang.Thread.run(Thread.java:856)
Community
  • 1
  • 1
Ripal Tamboli
  • 562
  • 1
  • 4
  • 16

1 Answers1

3

Don't use con.connect() after the getOutputStream() call, as the second will have called connect() anyways.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
  • Thanks for your reply. But here my question is if error occuring due to using con.connect() after the getOutputStream() then why it is not throwing the same exception for other APIS as well?? it is only throwing exception for calling one API. For rest of the APIS it is working fine. – Ripal Tamboli Aug 31 '13 at 07:12
  • 2
    You mean, for other API calls. If they are before the connect(), that's because there was no exception up to that point. If they are after that call, they do not get executed, so why would there be an error? ... have you played around, or read the code path, or read the exception? – Tassos Bassoukos Aug 31 '13 at 07:28
  • Hi Tassos..let me know if you still facing problem to understand what i am saying. :) – Ripal Tamboli Aug 31 '13 at 09:05
  • 1
    @RipalTamboli some API calls need an open connection (`getOutputStream` is an example) and they automatically open the connection when it is not already open. Some others don't need an open connection, they can safely (and sometimes must) be called before `connect`. – Henry Aug 31 '13 at 09:10
  • @Henry: Server side API is created in PHP. And PHP team following the same approach in all API. Now coming to your point, what you are trying to say is if Server side APIs are following the same approach in implementation, still we need to take care about your above point. Right??? – Ripal Tamboli Aug 31 '13 at 09:15
  • 1
    I was talking about Java's HTTP API. This has nothing to do with the server side implementation. – Henry Aug 31 '13 at 09:18
  • @RipalTamboli *What happened when you tried* the suggestion in this answer? Or are you just going to argue about it forever and never find out? – user207421 Aug 31 '13 at 09:23
  • @EJP: i have tried suggestion given by Tassos and still getting the same error. thats why i continue looking for help. BTW, i am not arguing. i am looking for help so my work can appear to next level. – Ripal Tamboli Aug 31 '13 at 09:31
  • It seems that someone misused the down rate option :( – Ripal Tamboli Aug 31 '13 at 09:40
  • @RipalTamboli You can't have got exactly the same exception because at least the stack trace will be different. Post it, by which I mean edit it into your question, not put it here as a comment. – user207421 Sep 01 '13 at 10:03