繁体   English   中英

api代码android studio的问题

[英]issue with api code android studio

我的代码有一些问题。 我必须使用 JSONParser 阅读,我在我的代码上加上了下划线,它说问题是我需要 try/catch 子句,但是当我添加整个代码时,它带有下划线,它说我必须对我的 api 代码做一些事情。

这是我的代码:

 public void onResponse(JSONObject response){
                            JSONArray quest=response.getJSONArray("students");
                            for(int i=0;i<quest.length();i++){
                                JSONObject question=quest.getJSONObject(i);
                                String name=question.getString("name");
                                String q=question.getString("question");


                                label.append(name+" asked "+ q);
                            }
                        }

谢谢!

建议改用 HttpUrlConnection,因为不推荐使用 HttpClient。 进一步研究; http://developer.android.com/reference/java/net/HttpURLConnection.html

 void hitService() {

        String resp = "";

        HttpClient client = new DefaultHttpClient();
        String postURL = serviceUrl;

        HttpPost post = new HttpPost(postURL);


            HttpResponse response = client.execute(post);
            // Convert the response into a String
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {

                resp = EntityUtils.toString(resEntity);
                Log.i(TAG, resp);
            }
        } catch (UnsupportedEncodingException uee) {
            uee.printStackTrace();
        } catch (ClientProtocolException cpe) {
            cpe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return resp;

    }

HttpClient 和 HttpPost 已弃用,在 API 级别 23 中已删除。 这就是为什么您在 Android Studio 中收到警告将您的网络连接更改为 HttpURLConnection 而不是 HttpClient。

对于 HttpURLConnection 的实现,请检查指南

即使您需要将 HttpClient 与目标 SDK =>23 一起使用,Android 也提供了对库的支持,您需要在 build.gradel 中添加以下行

 android{
useLibrary 'org.apache.http.legacy'}

注意:他们提供了从 Android 中删除 HttpClient 的原因的明确文档,并且他们在此处提供了新网络连接的支持和实现

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM