volley JSON请求数据

来源:互联网 发布:穿越火线网络异常23 2 编辑:程序博客网 时间:2024/04/29 02:45

今天学习JSON请求数据,代码写好后出错:

1.运行出错      E/AndroidRuntime(11124):java.lang.ArrayIndexOutOfBoundsException: length=96; index=96

解决方法:重新运行源代码,断点调试,查看两个程序运行轨迹,发现参数值不一样,修改后重新运行,成功!

2.请求数据url=http://m.weather.com.cn/data/101010100.html这是在别人博客里看到的url地址,因为我并不知道国家气象局的JSONurl,运行时返回的Response,直接运行new Response.ErrorListener() {},断点调试后logcat输出出错信息:

org.json.JSONException:Value<html>of type java.lang.String cannot be converted to JSONObject

打印输出了得到的数据,得到的数据是一个html页面源码,上网查资料,http://blog.csdn.net/forlong401/article/details/18256269,http://m.blog.csdn.net/blog/u011695847/17090879,http://www.cnblogs.com/sonicit/archive/2013/03/24/2979524.html。

解决方法:a.觉得可能是volley包中没有考虑到这个“ufeff"”前缀问题,所以重新写一个JsonObjectUTF8Request类,重写一下里面的处理方法。

package com.example.volleyRequest;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;

public class JsonObjectUTF8Request extends JsonObjectRequest {

 public JsonObjectUTF8Request(int method, String url,
   JSONObject jsonRequest, Listener<JSONObject> listener,
   ErrorListener errorListener) {
  super(method, url, jsonRequest, listener, errorListener);
  // TODO Auto-generated constructor stub
 }

 protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
  try {
   // solution 1:
   String jsonString = new String(response.data, "UTF-8");
   Log.v("jsonString", jsonString.toString());

   return Response.success(new JSONObject(jsonString),
     HttpHeaderParser.parseCacheHeaders(response));
  } catch (UnsupportedEncodingException e) {
   return Response.error(new ParseError(e));
  } catch (JSONException je) {
   return Response.error(new ParseError(je));
  }
 }

}
运行之后,问题仍然存在。

b.求助qq群的牛人。经过探讨,原来是输入的url不正确,重新换了url,程序成功运行。

3.程序出现问题时一定不要着急,慢慢的缕清思路,日积月累。另附上国家气象局接口,http://wenku.baidu.com/view/ea286102bb68a98271fefad8.html,大家调用的时候检验一下,我没验证。

明天开始GSON.

0 0