HttpPost не работает в Android SDK 23

есть метод в моем приложении для Android, который использует класс HttpPost. Он отлично работал с целевым SDK 4.4.2, но я внес некоторые изменения и сделал целевой SDK 23 (6.0). Теперь класс HttpPost выдает ошибку. Я также читал о HttpUrlConnection, но не знаю, как его использовать. Вот моя BaseActivity, я расширяю этот класс в других моих действиях, и это работает с SDK 4.4.2, но не с sdk23, пожалуйста, помогите

public class BaseActivity extends ActionBarActivity {
private Toolbar mToolbar;
private NavigationDrawerFragment mNavigationDrawerFragment;
LayoutInflater inflater;
FrameLayout container;
private static final int socketTimeout = 30000;
private static final int maxTries = 4;
Context context;
ProgressDialog dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

protected void setBaseContentView(int LayoutId) {
    setContentView(R.layout.drawer_layout);
    mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
            .findFragmentById(R.id.fragment_drawer);
    mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
    container = (FrameLayout) findViewById(R.id.container);
    inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    container.addView(inflater.inflate(LayoutId, null));
}

/* for service */
public void getVolleyTask(Context context, final IVolleyReponse responseContext, String URL) {
    RequestQueue request = Volley.newRequestQueue(context);
    StringRequest strReq = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                System.out.println("what");
                if (response != null) {
                    JSONArray _array = new JSONArray(response);
                    responseContext.ResponseOk(_array);
                } else {
                    responseContext.ResponseOk(null);
                }
            } catch (Exception e) {
                e.printStackTrace();
                responseContext.ResponseOk(null);
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            responseContext.ErrorBlock();
        }
    });
    strReq.setRetryPolicy(new DefaultRetryPolicy(socketTimeout, maxTries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    request.add(strReq);
}

public void getVolleyPostTask(Context context, final IVolleyJSONReponse jsonResponseContext, String URL,
        JSONObject obj) {
    RequestQueue request = Volley.newRequestQueue(context);
    JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL, obj,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    jsonResponseContext.ResponseOk(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    jsonResponseContext.ErrorBlock();
                }
            }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            return headers;
        }
    };
    myRequest.setRetryPolicy(
            new DefaultRetryPolicy(socketTimeout, maxTries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    request.add(myRequest);
}

/*********** Json Response **********/

public void JSONRequest(IJSONStringResponse context, String URL, JSONObject obj, int position) {
    JSONTask task = new JSONTask(context, URL, obj, position);
    task.execute();
}

private class JSONTask extends AsyncTask<Void, Void, String> {
    String URL;
    JSONObject obj;
    IJSONStringResponse context;
    int position;

    public JSONTask(IJSONStringResponse context, String URL, JSONObject obj, int position) {
        this.context = context;
        this.URL = URL;
        this.obj = obj;
        this.position = position;
    }

    // ----------------------------------------------------------------------
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(BaseActivity.this, "", "Please Wait...");
    }

    // ----------------------------------------------------------------------
    @Override
    protected String doInBackground(Void... params) {
        String object = null;
        try {
            object = getJSON(URL, obj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    protected void onPostExecute(String result) {
        context.IJson(result, position);
        dialog.dismiss();
    }

    //Here the HTTPPOST class is depricated and not working with sdk 23 and                            // same class is working fine with sdk 4.4.2
    private String getJSON(String URL, JSONObject obj) throws JSONException {
        String responseString = null;
        try {
            HttpPost httppost = new HttpPost(URL);
            StringEntity se = new StringEntity(obj.toString(), HTTP.UTF_8);
            httppost.setHeader("Content-Type", "application/json");

            httppost.setEntity(se);

            HttpParams httpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
            HttpClient httpclient = new DefaultHttpClient(httpParams);
            HttpResponse httpResponse = httpclient.execute(httppost);

            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            System.out.println("status code is" + statusCode);
            HttpEntity entity = httpResponse.getEntity();
            responseString = EntityUtils.toString(entity, "UTF-8");
            System.out.println("response string" + responseString);
            // Log.i("RESPONSE XML ------> ", "-----> " + responseString);
            return responseString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseString;

    }
}

}


person ravi raghav    schedule 12.03.2016    source источник
comment
проверьте этот ответ, это говорит вам, как вы можете отправлять данные на URL-адрес, используя HttpURLConnection stackoverflow.com/questions/34835154/< /а>   -  person Pankaj Nimgade    schedule 12.03.2016


Ответы (2)


В настоящее время я использую OKHTTP и до сих пор не сталкивался с проблемами. Это здорово и просто в использовании.

person Vucko    schedule 12.03.2016