0

我有 Jersey 实现的 Restful Web Service。我通过 HTTP 客户端从 Android 连接以获取数据。它在 API 级别 10 和更早的版本中运行良好,但在 API 级别 11 或更高版本中无法正常工作。我很感激任何帮助。我在这些版本中有一个 nullPointerException。

public String getBaseURI(String str) {
        String result = "";
        try {
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpGet getRequest = new HttpGet(ServerAddress + str);
            getRequest.addHeader("accept", "application/json");
            HttpResponse response = httpClient.execute(getRequest);
            result = getResult(response).toString();
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } 
        return result;
    }

private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
        if (response.getStatusLine().getStatusCode() != 201) 
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        StringBuilder result = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
        String output;
        while ((output = br.readLine()) != null) 
            result.append(output);
        return result;      
    }

标签: Android运行时

logcat 异常:

Exception: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.android.internal.os.LoggingPrintStream.Prrintln(LogiingPrintStream.java.298)
at Client.getBaseURI (Client.java:66)

当我调用休息服务时,例如: String str = client.getBaseURI("task/project/get/" + user);
我得到错误。

private void listViewSet() {

        ListView lv = (ListView) this.findViewById(R.id.listView);
        lv.setAdapter(new MultiAdapter(this));

        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

                switch (pos) {
            case ADD:
            String str = client.getBaseURI("task/project/get/" + user);// Json format
                        ......
                }
            }
        });
    }
4

1 回答 1

0

您是否在单独的线程上执行 HTTP 请求(AsyncTask例如,使用 )?

一些较新的 API(尤其是 ICS,根据我的经验)强制要求您在单独的线程上执行网络连接,以免阻塞 UI 线程。网络连接可能很长而且很昂贵,因此您永远不想在 UI 线程上执行它们。这样做可能会阻止 UI 被绘制到屏幕上,导致您的应用程序强制关闭,使您的应用程序对用户显得迟钝等等。

于 2012-06-05T20:56:25.827 回答