无法从Android中的Web服务接收完整响应

时间:2014-10-30 13:17:15

标签: android web-services

我通过发布参数编写用于从服务获取json数据的代码,但我没有从webservice获得完整响应,就像我想要显示500个定时问题,但它只显示20个问题,当检查服务时高级休息客户端然后webservices提供完整的响应,但通过Android程序我没有得到完整的响应,我的代码: -

public static String postRequest(Context ct, String url,
            List<NameValuePair> postvalues) throws IllegalStateException,
            IOException
{
    mContext = ct;
    HttpPost post = null;
    String content = null;

    HttpParams params = new BasicHttpParams();
    int timeoutConnection = 1000 *1;
    HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);


    int timeoutSocket = 60 * 1000 *30;
    HttpConnectionParams.setSoTimeout(params, timeoutSocket);

    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

    HttpClient client = new DefaultHttpClient(params);
    String srvURL = mainurl + url;

    // Log.i("Webservise", "url="+srvURL);
    post = new HttpPost(srvURL);
    post.setHeader("Content-type",
            "application/x-www-form-urlencoded;charset=UTF-8");
    post.setHeader("Accept-Charset", "utf-8");
    post.setEntity(new UrlEncodedFormEntity(postvalues, HTTP.UTF_8));

    try {

        HttpResponse response = client.execute(post);
        HttpEntity entity = response.getEntity();

        is = entity.getContent();

        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 32);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            json = sb.toString();
            // Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        Log.e("Webservice call", "Response kp=" + json.toString());

    } catch (SocketTimeoutException ex) {
        Toast.makeText(ct, "Request time out", Toast.LENGTH_SHORT).show();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception ex) {
        // Do something for all other types of exception.
    }

    // 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 json;

}

1 个答案:

答案 0 :(得分:0)

这对我有用。我没有使用BufferedReader,而是使用EntityUtil将响应转换为字符串。 试试这个

try{
   HttpResponse response = client.execute(post);

   json = EntityUtils.toString(response.getEntity());

    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    }