错误java.net.ConnectException:24000ms后无法连接:ECONNREFUSED(连接被拒绝)

时间:2017-03-16 11:14:40

标签: android json connectexception

我在网上搜了好几个小时,才发现this as answer。但是,我不知道在我的代码中将其用于何处。

    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;
        }

    }

我尝试增加超时,只有在使用移动数据时才能看到此问题,而不是在WiFi上。真的很感激任何帮助..

1 个答案:

答案 0 :(得分:0)

服务器无法发送响应:确保后端在提及的IP和端口上正常工作。