HTTP客户端API级别11或更高版本在Android中 [英] HTTP Client API level 11 or greater in Android

查看:139
本文介绍了HTTP客户端API级别11或更高版本在Android中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有泽西实现RESTful Web服务。 我从Android的通过HTTP客户端连接来获取数据。它工作在API级别10和旧版本的罚款,但不是在API级别11或更高。我AP preciate的任何帮助。我在这些版本NullPointerException异常。

 公共字符串getBaseURI(字符串str){
        字符串结果=;
        尝试 {
            的HttpParams httpParameters =新BasicHttpParams();
            INT timeoutConnection = 3000;
            HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
            INT timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
            DefaultHttpClient的HttpClient =新DefaultHttpClient(httpParameters);
            HTTPGET调用getRequest =新HTTPGET(ServerAddress + STR);
            getRequest.addHeader(接受,应用/ JSON);
            HTT presponse响应= httpClient.execute(调用getRequest);
            结果=的getResult(响应)的ToString();
            。httpClient.getConnectionManager()关闭();
        }赶上(例外五){
            的System.out.println(e.getMessage());
        }
        返回结果;
    }

私人的StringBuilder的getResult(Htt的presponse响应)抛出IllegalStateException异常,IOException异常{
        如果(response.getStatusLine()的getStatus code()!= 201)
            抛出新的RuntimeException(失败:HTTP错误code:+ response.getStatusLine()的getStatus code());
        StringBuilder的结果=新的StringBuilder();
        的BufferedReader BR =新的BufferedReader(新的InputStreamReader((response.getEntity()的getContent())),1024。);
        字符串输出;
        而((输出= br.readLine())!= NULL)
            result.append(输出);
        返回结果;
    }
 

标签:AndroidRuntime

在logcat的异常:

 例外:致命异常:主要
显示java.lang.NullPointerException
在com.android.internal.os.LoggingPrintStream.Prrintln(LogiingPrintStream.java.298)
在Client.getBaseURI(Client.java:66)
 

当我调用REST服务,如: 字符串str = client.getBaseURI(任务/项目/得/+用户);
我得到的错误。

 私人无效listViewSet(){

        ListView的LV =(ListView控件)this.findViewById(R.id.listView);
        lv.setAdapter(新MultiAdapter(本));

        lv.setOnItemClickListener(新OnItemClickListener(){
            公共无效onItemClick(适配器视图<>母公司视图中查看,INT POS,长I​​D){

                开关(POS){
            案例地址:
            字符串str = client.getBaseURI(任务/项目/得/+用户); // JSON格式
                        ......
                }
            }
        });
    }
 

解决方案

您执行一个单独的线程HTTP请求(使用的AsyncTask ,例如)<? / P>

一些新的API(特别是ICS,以我的经验)的强制要求你在一个单独的线程中执行的网络连接,以便不阻塞UI线程。网络连接可能是潜在漫长而昂贵的,所以你的永远的要在UI线程上执行它们。这样做可能prevent被绘制到屏幕上的用户界面,使您的应用程序强制关闭,使您的应用程序出现laggy给用户,等等。

I have Restful Web Service implemented by Jersey. I connect from Android via HTTP client to fetch the data. It works fine in API level 10 and older versions but not on API level 11 or greater. I appreciate for any help. I have a nullPointerException in these versions.

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;      
    }

Tag : AndroidRuntime

The logcat exception:

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

when I call a rest service such as: String str = client.getBaseURI("task/project/get/" + user);
I get the Error.

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
                        ......
                }
            }
        });
    }

解决方案

Are you performing the HTTP request on a separate thread (using an AsyncTask, for example)?

Some of the newer APIs (especially ICS, in my experience) forcefully require you to perform network connections on a separate thread so as to not block the UI thread. Network connections can be potentially long and expensive, so you never want to perform them on the UI thread. Doing so might prevent the UI from being drawn to the screen, cause your application to force close, make your application appear laggy to the user, etc.

这篇关于HTTP客户端API级别11或更高版本在Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆