duanhuang7591 2014-12-24 15:10
浏览 167
已采纳

为android json设置httprequest超时

This is my code so far, i changed it according to many posts i found on stackoverflow, however i can't seem to be able to make it work, it works fine, but sometimes it is stuck on the progress bar and it keeps spinning until the app crashes, i am trying to set the timeout so that if the connection is not successful it will stop instead of having the app crash .

I'm not sure if i am using the HttpConnectionParams.setSoTimeout and HttpConnectionParams.setConnectionTimeout the right way,

this is the JSON code

public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) 
    {
        try 
        {
             HttpParams httpParameters = new BasicHttpParams();
             HttpConnectionParams.setSoTimeout(httpParameters, 4000);
             HttpConnectionParams.setConnectionTimeout(httpParameters, 4000);

            if(method.equals("POST"))
            {
                HttpClient  httpClient = new DefaultHttpClient(httpParameters);
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null)
                {
                     is = httpEntity.getContent();
                     if(is != null)
                     {
                         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
                         StringBuilder sb = new StringBuilder();
                         String line = null;
                         while ((line = reader.readLine()) != null) 
                         {
                             sb.append(line + "
");
                         }
                         is.close();
                         json = sb.toString();
                         jObj = new JSONObject(json);
                     }
                }
            }
            else if(method.equals("GET"))
            {
                HttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null)
                {
                     is = httpEntity.getContent();
                     if(is != null)
                     {
                         BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
                         StringBuilder sb = new StringBuilder();
                         String line = null;
                         while ((line = reader.readLine()) != null) 
                         {
                             sb.append(line + "
");
                         }
                         is.close();
                         json = sb.toString();
                         jObj = new JSONObject(json);
                     }
                }
            }           
        } 
        catch (ConnectTimeoutException e) 
        {
            //Here Connection TimeOut excepion    
            Log.e("connection error time OUT", "ok");
         }
        catch (UnsupportedEncodingException e) 
        {
            e.printStackTrace();
        } catch (ClientProtocolException e) 
        {
            e.printStackTrace();
        } catch (IOException e) 
        {
            e.printStackTrace();
        }
        catch (Exception e) 
        {
            Log.e("Buffer Error", "error converting result " + e.toString());
        }
        return jObj;

    }

And this is the AsyncTask To load items from the php page.

class GetSpecialOffers extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("loading items, please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            try 
            {
                int success=0;
                JSONObject json = jParser.makeHttpRequest(url_items, "GET",params);
                if(json != null)
                {
                    success = json.getInt(TAG_SUCCESS);
                }
                if (success == 1) 
                {
                    successValue = 1;
                    items = json.getJSONArray(TAG_SPECIAL_ITEM);

                    for (int i = 0; i < items.length(); i++) 
                    {
                        JSONObject c = items.getJSONObject(i);

                        specialid = c.getString(TAG_SPECIAL_ID);
                        specialname = c.getString(TAG_SPECIAL_NAME);
                        specialprice = c.getString(TAG_SPECIAL_PRICE);
                        specialimage = c.getString(TAG_SPECIAL_IMAGE);
                        specialdate = c.getString(TAG_SPECIAL_DATE);

                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_SPECIAL_ID, specialid);
                        map.put(TAG_SPECIAL_NAME, specialname);
                        map.put(TAG_SPECIAL_PRICE, specialprice);
                        map.put(TAG_SPECIAL_IMAGE, specialimage);
                        map.put(TAG_SPECIAL_DATE, specialdate);

                        SpecialList.add(map);
                    }
                } 
                else 
                {
                    successValue = 0;
                }
            } 
            catch (JSONException e) 
            {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String file_url) 
        {
            pDialog.cancel();
            if (successValue==1)
            {
                adapter = new SpecialAdapter(getActivity(), SpecialList);
                lVSpecial.setAdapter(adapter);
            }
            else
            {
                NoSpecialOffersFound();
            }
        }

    }
  • 写回答

1条回答 默认 最新

  • drasebt1835 2014-12-24 15:59
    关注

    Use this code,this works for me.

    JSONParser.java

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.util.Log;
    
    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {
    
        }
    
        // function get json from url
        // by making HTTP POST or GET mehtod
        public JSONObject makeHttpRequest(String url, String method,
                List<NameValuePair> params) {
    
            // Making HTTP request
            try {
    
                // check for request method
                if(method == "POST"){
                    // request method is POST
                    // defaultHttpClient
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                }else if(method == "GET"){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
    
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }           
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "
    ");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。