我想爲我的應用程序獲取json數據。我怎樣才能在android中獲得JSON響應?
這裏是CallAPI.java
類來獲得響應
public class CallAPI extends AsyncTask<String,String,String> {
String jsonStr="";
private static final String url="https://api.litzscore.com/rest/v2/recent_matches/";
@Override
protected String doInBackground(String... params) {
List<NameValuePair> param=new ArrayList<>();
param.add(new BasicNameValuePair("access_token",""));//here i am added my access token
ServiceHandler sh=new ServiceHandler();
jsonStr=sh.makeServiceCall(url,ServiceHandler.GET,param);
try{
JSONObject obj=new JSONObject(jsonStr);//I got error here
Log.e("response",""+obj.toString());
}
catch (JSONException e){
e.printStackTrace();
}
return null;
}
}
這裏是我的JSON ServiceHandler.java
public class ServiceHandler {
static String response=null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
Log.e("URL",""+url);
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("RESPONSE",response);
return response;
}
}
這裏是我的錯誤
org.json.JSONException: Value ���nҩV�͗Qo�0ǿ��ץ`�o���j+� of type java.lang.String cannot be converted to JSONObject
如果我叫從本地服務器,如文件wammp,xampp然後它工作正常。 請幫我解決這個問題。
'nҩV͗Qo0ǿץ'OJ +'JSON響應無效的JSON字符串 –
這就是問題,所以會出現什麼我做? –
從Log.e(「RESPONSE」,response)中的服務器得到什麼;'line? –