Android JSON makeHttpRequest在移动数据上返回null

时间:2017-09-14 00:35:43

标签: android json httprequest

我有一个应用程序可以从我的网站访问一些JSON数据。该应用程序在我的手机和我测试的手机上的WIFI和移动数据上运行良好。但是,一些用户在移动数据上遇到问题。当他们使用WIFI时,它运行正常,但它不适用于他们的移动数据。

以下是获取json数据的代码。

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from url
        JSONObject json = jParser.makeHttpRequest(url, "GET", params);

似乎json为手机上的移动数据返回null。我不确定为什么。

这是JSON Parsers的类

 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 + "\n");
        }
        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;

}
 }

1 个答案:

答案 0 :(得分:0)

尝试将连接和套接字超时设置为合理的时间 - 在您的设备上测试数据连接速度稍慢的区域,以便确定应该多长时间。

以下是一个很好的答案以及如何执行此操作的示例: https://stackoverflow.com/a/1565243/5095571