我已经注意到,与同一个服务器进行通信的应用程序相比,我的http请求往往花费大量时间。它使我的应用程序呆滞,我想知道是否有更好的方法来发出这些请求并更新UI。
目前,我使用这种方法进行发布请求
public String postRequest(List<NameValuePair> nameValuePairs, String method_name) {
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mysite.com/api/"+method_name);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Authorization", "Basic somestuff");
try {
// Add your data
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
result = rd.readLine();
return result;
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
在我的UI线程(即我的Fragment类)中,我在这样的Async Task中使用了它
class MakeRequest extends AsyncTask<Integer, Integer, String> {
protected String doInBackground(Integer... counter) {
String result = "";
String method_name = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", value));
nameValuePairs.add(new BasicNameValuePair("name", name));
method_name = "petition/setPetition";
result = fixr.postRequest(nameValuePairs, method_name);
JSONObject jsonFile = new JSONObject(result);
if(!jsonFile.has("error")){
//Parse JSON using GSON
return "success";
}else{
return jsonFile.getString("error");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String jsonResult) {
try {
if(jsonResult != null){
//update UI
}else{
//Error message
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我想对此进行优化,以便用户可以在我的应用程序上获得真正的流畅体验。我愿意使用第三方http库,或者是否有反对使用AysncTasks的争论,也许也可以反对runOnUiThread()
。
Volley Library更好,例如http,https等
。https
: //developers.google.com/live/shows/474338138此处的微型示例:https : //github.com/ogrebgr/android_volley_examples/blob/master/src/com/ github / volley_examples / Act_SimpleRequest.java
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句