0

I've searched many hours across the net, only found this as answer. However, I don't know where to use this in my code.

    public final static int GET=1;
    public final static int POST=2;
    public final static int PUT=3;
    public final static int DELETE=4;
    public final static String TAG="JSONParser";

    Context context;
    public JSONParser(Context context){
        super();
        this.context=context;
        //this.deviceId = Utility.getDeviceId(this.context);
    }
    public String getResponseString(String url,int method,String basicAuth){
        return makeServiceCall(url,method,null,basicAuth);
    }

    public String getResponseString(String url, int method, ContentValues params, String basicAuth){
        return  makeServiceCall(url,method,params,basicAuth);
    }
    public JSONObject getJSONFromUrl(String url, int method, String basicAuth){
        return getJSONFromUrl(url,method,null,basicAuth);
    }
    public JSONObject getJSONFromUrl(String url, int method, ContentValues params, String basicAuth){
        Log.e(TAG, "getJSONFromUrl: " );
        JSONObject json=null;
        try{
            String jsonString=makeServiceCall(url,method,params,basicAuth);
            if(jsonString!=null){
                json=new JSONObject(jsonString);
            }
            return json;
        }catch (JSONException e){
            Log.e(TAG, "Error parsing data "+e.toString() );
            return json;
        }
    }
    public JSONArray getJSONArrayFromUrl(String url, int method, String basicAuth){
        return  getJSONArrayFromUrl(url,method,null,basicAuth);
    }
    public JSONArray getJSONArrayFromUrl(String url, int method, ContentValues params, String basicAuth){
        Log.e(TAG, "getJSONArrayFromUrl" );
        JSONArray jsonArray=null;
        try{
            String jsonString=makeServiceCall(url,method,params,basicAuth);
            if(jsonString!=null){
                Log.e("jsonString",jsonString );
                jsonArray=new JSONArray(jsonString);
            }
            return jsonArray;
        }catch (JSONException e){
            Log.e(TAG, "Error parsing data "+e.toString() );
            return jsonArray;
        }
    }
    private String makeServiceCall(String address, int method,ContentValues params, String basicAuth) {
        Log.e(TAG, "makeServiceCall");
        String result = null;
        URL url = null;
        HttpURLConnection urlConnection = null;
        OutputStream out;
        InputStream in;
        try {
            address = URLDecoder.decode(address, "UTF-8");
            Log.e(TAG, "makeServiceCall: Url: " + address);
        } catch (Exception e) {

        }


            try {

                url = new URL(address);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(24000);
                urlConnection.setReadTimeout(24000);
                urlConnection.setAllowUserInteraction(false);
                urlConnection.setInstanceFollowRedirects(true);

                if (method == POST) {
                    urlConnection.setRequestMethod("POST");
                    urlConnection.setDoOutput(true);
                    urlConnection.setDoInput(true);
                } else if (method == GET) {
                    urlConnection.setRequestMethod("GET");
                } else if (method == PUT) {
                    urlConnection.setRequestMethod("PUT");
                    urlConnection.setDoOutput(true);
                } else if (method == DELETE) {
                    urlConnection.setRequestMethod("DELETE");
                    urlConnection.setDoOutput(true);
                }
                //urlConnection.setRequestProperty("Content-Type","application/x-www-from-urlencoded");
                //urlConnection.setRequestProperty("Content-Type","application/from-data");
                //urlConnection.setRequestProperty("charset","utf-8");
                urlConnection.setRequestProperty("Accept", "application/json");
                //urlConnection.setRequestProperty("Accept","text/html");

                if (basicAuth != null && basicAuth.length() > 0) {
                    urlConnection.setRequestProperty("Authorization", basicAuth);
                }
                if (method != GET) {
                    if (params != null) {
                        StringBuilder postData = new StringBuilder();
                        for (String key : params.keySet()) {
                            if (postData.length() != 0) postData.append('&');
                            postData.append(URLEncoder.encode(key, "UTF-8"));
                            postData.append('=');
                            postData.append(URLEncoder.encode(String.valueOf(params.get(key)), "UTF-8"));
                        }
                        byte[] outData = postData.toString().getBytes("UTF-8");
                        urlConnection.setRequestProperty("Content-Length", Integer.toString(outData.length));
                        out = new BufferedOutputStream(urlConnection.getOutputStream());
                        out.write(outData);
                        out.close();
                    }
                }
                urlConnection.connect();
                in = new BufferedInputStream(urlConnection.getInputStream());
                result = inputStreamToString(in);
                Log.e(TAG, "ServerResponse" + result);

            } catch (Exception e) {
                Log.e("makeServiceCall: ", "Error" + e.toString());
                Toast.makeText(context,context.getResources().getString(R.string.please_try_later),Toast.LENGTH_SHORT).show();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }


        return result;
    }

    /*
    private HttpClient createHttpClientWithDefaultSocketFactory(Object o, Object o1) {
    }
*/
    private static String inputStreamToString(InputStream in) {
        String result="";
        if(in==null){
            return result;
        }
        try{
            BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
            StringBuilder out=new StringBuilder();
            String line;
            while((line=reader.readLine())!=null){
                out.append(line);
            }
            result=out.toString();
            reader.close();
            return result;
        }catch(Exception e){
            Log.e( "inputStreamToString: ","Error"+e.toString() );
            return result;
        }

    }

I tried increasing timeout, this problem is seen only when using mobile data, not on WiFi. Any Help would be really really appreciated..

Community
  • 1
  • 1
mrLovaLova
  • 187
  • 2
  • 14
  • If it works using WiFi, but not mobile data, maybe you are trying to connect to a local address? By the way, the answer you found just suggests to reconnect a few times, so you just have to implement a for-loop. – Tyrmos Mar 16 '17 at 12:48
  • ERCONNREFUSED means that the port of the server is refusing connection. Maybe it's rate limiting you and forcing a close on the connection? – GregP Mar 16 '17 at 15:53
  • @Tyrmos Yes, I'd implemented a for-loop, but it breaks out. – mrLovaLova Mar 17 '17 at 03:35
  • Even If it times out, The app shouldn't crash, atleast. – mrLovaLova Mar 17 '17 at 03:36
  • Have you checked if the ip address you are using is local? – Tyrmos Mar 17 '17 at 08:08
  • Local, meaning associated with localhost? – mrLovaLova Mar 17 '17 at 09:04
  • More like your [private address](https://en.wikipedia.org/wiki/Private_network), commonly starts with 192.168 – Tyrmos Mar 17 '17 at 10:23
  • Yeah, it's starts with 192.168, so what's next? – mrLovaLova Mar 17 '17 at 11:46
  • There is the problem, you are using your private address, which is only reachable if you are connected to your private network. Thats why you can connect using WiFi, because thats connected to your Network. If you want to reach your program or whatever you have to use your external (or global) address. [Difference local and global IP address](http://stackoverflow.com/questions/26290754/difference-private-ip-and-public-ip) – Tyrmos Mar 17 '17 at 12:28

1 Answers1

0

The server couldn't send a response: Ensure that the backend is working properly at IP and port mentioned.

Karthik
  • 102
  • 13