【问题标题】:Application Crashing frequently on httprequest应用程序在 httprequest 上经常崩溃
【发布时间】:2015-05-12 06:31:58
【问题描述】:

从服务器获取数据时,我经常出错。从过去几周开始,它正在发生。有时它有效,有时则无效。 logcat显示错误在jsonparser文件中,而

httpclient.execute

但无法纠正为什么?

exercise.java

List<NameValuePair> parametres = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            parametres.add(new BasicNameValuePair("inputChar", inputChar));



            **JSONObject json = jsonParser.makeHttpRequest(url_display_user,
                    "GET", parametres);**


            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    exercises = json.getJSONArray(TAG_RESPONSE);
                    // looping through All RESPONSE
                    for (int i = 0; i < exercises.length(); i++) {
                        JSONObject jsonobj = exercises.getJSONObject(i);
                        // Storing each json item in variable
                        String id = jsonobj.getString(TAG_ID);
                        String activityname = jsonobj.getString(TAG_ACTIVITY_NAME);
                        String metvalue = jsonobj.getString(TAG_METVALUE);
                        // creating new HashMap
                        HashMap<String, String> map = new HashMap<String, String>();
                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_ACTIVITY_NAME, activityname);
                        map.put(TAG_METVALUE, metvalue);
                        // adding HashList to ArrayList
                        exerciseitems.add(map);

                    }
                    return json.getString(TAG_MESSAGE);

                } else {
                    return json.getString(TAG_MESSAGE);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;

jsonparser.java

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();

                System.out.println(is + "post");

            }else if(method == "GET"){
                System.out.println("1");
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                System.out.println("2");
                String paramString = URLEncodedUtils.format(params, "utf-8");
                System.out.println("3");
                url += "?" + paramString;
                System.out.println("4");
                HttpGet httpGet = new HttpGet(url);
                System.out.println("5");

                HttpResponse httpResponse = httpClient.execute(httpGet);
                System.out.println("6");
                HttpEntity httpEntity = httpResponse.getEntity();
                System.out.println("7");
                is = httpEntity.getContent();
                System.out.println(is + "get");
            }           


        } 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 + "\n");
            }
            is.close();
            json = sb.toString();

            Log.i("TagCovertS", "["+json+"]");


        } 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;

    }

}

我在获取数据时收到此错误

还有一个错误

【问题讨论】:

  • 嗨,你能检查一下你在这个变量“url_display_user”中传递了什么吗?
  • url_display_user = "bharatwellness.com/exercise_metvalue.php"; @BhavdipPathar
  • 您是否在清单文件中添加了互联网权限
  • 是的,它有时可以完美运行,但有时不能。 @venkateshvenkey
  • 打印并检查每个makeHttpRequest(......)函数中返回的json对象

标签: android mysql json apache httpclient


【解决方案1】:

您可以使用启用 SSL 且比 httpclient 更安全的 httpurlconnection。

public class HttpPostData  extends AsyncTask<String, Void, String>{

    private String URL;
    private JSONObject jsonObjSend;
    int mResponseCode = -1;
    private Object totaltime;
    private long starttime;
    public HttpPostData(String URL, JSONObject jsonObjSend) {
        this.URL = URL;
        this.jsonObjSend = jsonObjSend;
    }

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


        String finalResult = null;
        URL url = null;

            HttpsURLConnection urlConnection = null;
            try {
                url=new URL(URL);
                urlConnection = (HttpsURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);  
                urlConnection.setDoInput(true);   

                urlConnection.setRequestMethod("POST");  
                urlConnection.setUseCaches(false);  
                urlConnection.setConnectTimeout(500);  
                urlConnection.setReadTimeout(500);  
                urlConnection.setRequestProperty("Content-Type","application/json"); 
                urlConnection.connect();  


                OutputStreamWriter out = new   OutputStreamWriter(urlConnection.getOutputStream());
                out.write(jsonObjSend.toString());
                out.close(); 
                starttime = System.currentTimeMillis();

                try {
                    mResponseCode = urlConnection.getResponseCode();
                    totaltime = System.currentTimeMillis() - starttime;
                    Log.e("HTTP POST Response Code:", ""
                            + mResponseCode);
                } catch (SSLPeerUnverifiedException e) {

                Log.e("Exception", Log.getStackTraceString(e));
            } catch (IOException e) {

                Log.e("Exception", Log.getStackTraceString(e));
                Log.e("HTTP POST Response Code(2):", ""
                        + mResponseCode);
            }

【讨论】:

  • 我在哪里可以添加我的参数?
  • 好的,我需要删除 json 解析器,我的 exercise.java 将涵盖所有内容?对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
相关资源
最近更新 更多