1

我正在创建一个从 Web 服务获取 Json 响应的应用程序。该应用程序位于 2 个文件中,一个 webclient 和一个 webserviceActivity。客户端回来了,我认为 logcat 正在打印 HTTP/1.1 200 OK。之后似乎有一个 JSONException。它可能与 url 中传递的第二个参数的格式有关,因为它是一个日期。我尝试传入一个字符串,但无济于事。我在这里完成的方法是从 sql.Date(yyyy mm dd) 创建一个日期对象并将其传递进去。这样我在 JSONException 之前从服务器得到了一点回报

这是文件。提前致谢。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.util.Log;

public class WebClient {

    private static final String TAG = WebClient.class.getSimpleName();



    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the
         * BufferedReader.readLine() method. We iterate until the BufferedReader
         * return null which means there's no more data to read. Each line will
         * appended to a StringBuilder and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /*
     * This is a test function which will connects to a given rest service and
     * prints it's response to Android Log with labels "Praeda".
     */
    public JSONObject connect(String url) {

        JSONObject json = null;
        HttpClient httpclient = new DefaultHttpClient();

        // Prepare a request object
        HttpGet httpget = new HttpGet(url);

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            Log.i(TAG, response.getStatusLine().toString());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result = convertStreamToString(instream);
                Log.i(TAG, result);

                // A Simple JSONObject Creation
                json = new JSONObject(result);



                // Closing the input stream will trigger connection release
                instream.close();

            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         return json;

    }
}

.

import java.sql.Date;

import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class WebserviceActivity extends Activity {

    private static final String TAG = WebserviceActivity.class.getSimpleName();
    TextView tv = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.textviewwebserviceresponse);

        WebClient rc = new WebClient();


        @SuppressWarnings("deprecation")
         Date d = new Date(2012, 9, 3);
        JSONObject jObj = rc
                .connect("http://212.169.27.217:84/rotaservice.asmx/GetRota?CarerID=36&RotaDate="+d);
         Log.e(TAG, "json obj = " + jObj.toString());
        tv.setText(jObj.toString());

    }// end of onCreate

}// end of class

.

09-03 19:52:00.490: I/global(21931): In close() at SocketHttpClientConnection
09-03 19:52:00.490: I/global(21931): call createSocket() return a new socket.
09-03 19:52:03.610: I/WebClient(21931): HTTP/1.1 200 OK
09-03 19:52:03.610: I/WebClient(21931): <?xml version="1.0" encoding="utf-8"?>
09-03 19:52:03.610: I/WebClient(21931): <string xmlns="http://tempuri.org/">{"0":{"StartDate":"","EndDate":"","Duration":"0","CallStatusID":"0","CallStatusName":"","ClientSurname":"","ClientForename":"","NeedName":"Out of range","CarerAwayReason":"","CallID":"","DoubleUpCallID":""}}</string>
09-03 19:52:03.620: W/System.err(21931): org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
09-03 19:52:03.620: W/System.err(21931):    at org.json.JSON.typeMismatch(JSON.java:111)
09-03 19:52:03.620: W/System.err(21931):    at org.json.JSONObject.<init>(JSONObject.java:158)
09-03 19:52:03.620: W/System.err(21931):    at org.json.JSONObject.<init>(JSONObject.java:171)
09-03 19:52:03.620: W/System.err(21931):    at com.carefreegroup.WebClient.connect(WebClient.java:87)
09-03 19:52:03.620: W/System.err(21931):    at com.carefreegroup.WebserviceActivity.onCreate(WebserviceActivity.java:31)
09-03 19:52:03.620: W/System.err(21931):    at android.app.Activity.performCreate(Activity.java:4543)
09-03 19:52:03.620: W/System.err(21931):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
09-03 19:52:03.620: W/System.err(21931):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
09-03 19:52:03.620: W/System.err(21931):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2260)
09-03 19:52:03.620: W/System.err(21931):    at android.app.ActivityThread.access$600(ActivityThread.java:139)
09-03 19:52:03.620: W/System.err(21931):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
09-03 19:52:03.620: W/System.err(21931):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-03 19:52:03.620: W/System.err(21931):    at android.os.Looper.loop(Looper.java:156)
09-03 19:52:03.620: W/System.err(21931):    at android.app.ActivityThread.main(ActivityThread.java:5045)
09-03 19:52:03.620: W/System.err(21931):    at java.lang.reflect.Method.invokeNative(Native Method)
09-03 19:52:03.630: W/System.err(21931):    at java.lang.reflect.Method.invoke(Method.java:511)
09-03 19:52:03.630: W/System.err(21931):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-03 19:52:03.630: W/System.err(21931):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-03 19:52:03.630: W/System.err(21931):    at dalvik.system.NativeStart.main(Native Method)
09-03 19:52:03.630: D/AndroidRuntime(21931): Shutting down VM
4

1 回答 1

0

该服务在字符串中返回带有 JSON 的 XML tag,您必须解析 XML 以获取它包含的 JSON。

于 2012-09-03T19:07:43.830 回答