HttpPost 在 android sdk 23 中不工作
HttpPost not working in android sdk 23
我的 android 应用程序中有一个使用 HttpPost class 的方法。它在目标 sdk 4.4.2 上运行良好,但我进行了一些更改并将目标 sdk 设为 23(6.0)。现在 HttpPost class 出错了。我也读过 HttpUrlConnection 但不知道如何使用它。这是我的 BaseActivity,我在我的其他活动中扩展了这个 class,这在 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;
}
}
}
看看这个:
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. -
建议:
要么使用遗留代码
android {
useLibrary 'org.apache.http.legacy'
}
我目前正在使用 OKHTTP,到目前为止我没有遇到任何问题。它很棒且易于使用。
我的 android 应用程序中有一个使用 HttpPost class 的方法。它在目标 sdk 4.4.2 上运行良好,但我进行了一些更改并将目标 sdk 设为 23(6.0)。现在 HttpPost class 出错了。我也读过 HttpUrlConnection 但不知道如何使用它。这是我的 BaseActivity,我在我的其他活动中扩展了这个 class,这在 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;
}
}
}
看看这个:
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. -
建议: 要么使用遗留代码
android {
useLibrary 'org.apache.http.legacy'
}
我目前正在使用 OKHTTP,到目前为止我没有遇到任何问题。它很棒且易于使用。