0
我有一個應用程序從我的網站訪問一些JSON數據。該應用在我的手機和我測試的手機上的WIFI和移動數據上工作正常。但是,一些用戶在移動數據上遇到問題。當他們使用WIFI時,它可以正常工作,但不適用於他們的移動數據。Android JSON makeHttpRequest在移動數據上返回null
下面是獲取json數據的代碼。
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from url
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
看來json的手機上的移動數據返回null。我不知道爲什麼。
這裏的類的JSON解析器
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;
}
}
我認爲當你使用移動數據,您的應用程序需要一定的時間要求服務器。您可以從服務器初始化接口等待響應。 – Dungnbhut
使用此答案爲api請求https://stackoverflow.com/questions/46086118/getting-json-info-from-php-to-android-studio?answertab=votes#tab-top –