1

我有一个字符串问题,我使用下面的代码从 URL 接收 JSON 数据,代码工作正常,但问题是我没有得到完整的数据,只有一半的 JSON 值来了,我想知道是否这是有原因的,如果是这样意味着如何解决这个问题。JSON字符串很大

            DefaultHttpClient http_client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(urls[0]);
            HttpResponse response = http_client.execute(httpGet);

            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            HttpEntity entity = response.getEntity();

            InputStream in = entity.getContent();
            StringBuffer out = new StringBuffer();
            byte[] b = new byte[4096];
            int n =  in.read(b);
            while(n>0){
                out.append(new String(b, 0, n));
                n = in.read(b);
            }

            String resultdata = out.toString();
            Log.d("Out data",resultdata);
4

4 回答 4

2

尝试使用 BufferedReader 获取这样的数据

    String line="";
   BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                // Read response 
     while ((line = rd.readLine()) != null) { 
               total.append(line); 
            }
   String jsonString=total.toString();
于 2013-03-15T05:54:06.293 回答
0
InputStream is = entity.getContent();
BufferedReader out = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = out.readLine()) != null) {sb.append(line + "\n");
            }
is.close();
String json = sb.toString();

尝试这个

于 2013-03-15T06:00:12.970 回答
0

你必须删除这条线

int n =  in.read(b);

并添加

  int n=0;

    while ((n= in.read(b)) != null)
于 2013-03-15T06:02:28.073 回答
0

请试试这个,

 public static JSONObject getJson(String url){

    InputStream is = null;
    String result = "";
    JSONObject jsonObject = null;

    // HTTP
    try {           
        HttpClient httpclient = new DefaultHttpClient(); // for port 80 requests!
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch(Exception e) {
        return null;
    }

    // Read response to string
    try {           
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();             
    } catch(Exception e) {
        return null;
    }

    // Convert string to object
    try {
        jsonObject = new JSONObject(result);            
    } catch(JSONException e) {
        return null;
    }

    return jsonObject;

}}
于 2013-03-15T06:05:23.360 回答