0

have a method in my android app which uses HttpPost class. It was working fine with targeted sdk 4.4.2 but i've made some changes and made the targeted sdk to 23(6.0). Now HttpPost class is giving error. I've also read about HttpUrlConnection but don't know how to use it. Here is my BaseActivity, i extend this class in my other activites and this is working find with SDK 4.4.2 but not with sdk23 please help

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;

    }
}

}

ravi raghav
  • 85
  • 11
  • check this answer, this tells you how you can post data to an url using HttpURLConnection http://stackoverflow.com/questions/34835154/how-to-send-a-name-value-pair-object-or-content-values-object-using-post-in-andr/34836954#34836954 – Pankaj Nimgade Mar 12 '16 at 10:53
  • Possible duplicate of [HttpPost giving error in API 23 android](http://stackoverflow.com/questions/35861428/httppost-giving-error-in-api-23-android) – Selvin Mar 12 '16 at 11:34

2 Answers2

4

Have a look at this: http connection android 6.0

According to the API 22-23 diff changes, the org.apache.http.* packages have been removed as of Android 6.0 (Marshmallow) API Level 23. -Kosso

Suggestions: Either use the legacy code

android {
       useLibrary 'org.apache.http.legacy'
   }

or better use HttpURLConnection (example)

Community
  • 1
  • 1
codewing
  • 674
  • 8
  • 25
  • adding org.apache.http.legacy jar file in eclipse project and it still doesn't work.Any other suggestions? except using HttpURLConnection – ravi raghav Mar 14 '16 at 04:28
  • You could try the OKHTTP lib like @Vucko mentioned in his answer but I would recomend using the native HttpURLConnection and using Android Studio :) – codewing Mar 14 '16 at 12:46
1

I'm currently using OKHTTP and I've encountered no trouble with it so far. It' great and easy to use.

Vucko
  • 7,371
  • 2
  • 27
  • 45