【问题标题】:httpclient.execute(httpget) Doesn't seem to work (Android)httpclient.execute(httpget) 似乎不起作用(Android)
【发布时间】:2015-05-01 10:37:43
【问题描述】:

我正在尝试从

获取每日报价

http://quotesondesign.com/api/3.0/api-3.0.json?callback=json

我在我的 onCreate 中调用了这个方法 但是当我尝试执行 httpclient.execute(); 它转义到 catch 语句...

我做错了什么?

我确实包含了<uses-permission android:name="android.permission.INTERNET" /> 在我的清单文件中。

public String getJson(){
        String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(quoteUrl);

        httpget.setHeader("Content-type", "application/json");

        InputStream inputStream = null;
        String result = null;
        String aJsonString = null;
        try {
            HttpResponse response = httpclient.execute(httpget);
            Toast.makeText(this, "It works", Toast.LENGTH_LONG).show();
            HttpEntity entity = response.getEntity();

            inputStream = entity.getContent();
            // json is UTF-8 by default
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            result = sb.toString();
            JSONObject jObject = new JSONObject(result);
            aJsonString = jObject.getString("quote");

        } catch (Exception e) {
            //Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show();
        }
        finally {
            try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
        }

        return aJsonString;
    }

编辑:这里是 onCreate()

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //verbergt notificatiebalk
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.splash);

    jsonstring = getJson();
    Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
    //Toast.makeText(this, jsonstring, Toast.LENGTH_LONG).show();
    //tot hier testen
    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            startActivity(i);

            finish();
        }
    }, SPLASH_TIME_OUT);
}

提前谢谢你!

【问题讨论】:

  • 删除Toast.makeText(this, "It works", Toast.LENGTH_LONG).show();
  • 您是从 AsyncTask 还是从主线程运行此代码?请发布更多代码
  • 我这样做了,但我不明白这应该如何解决?在执行()点仍然失败
  • 它在我的主线程中,你需要什么代码?我现在包含了我的 onCreate()

标签: android json android-studio httpclient


【解决方案1】:

更新:现在提供代码的实际答案:

private class AsyncQuoteDownload extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        String jsonData = getJson(); //or, if the jsonData var is available from everywhere, just put myR.run(); here, return null, and append the data directly in onPostExecute
        return jsonData;
    }

    @Override
    protected void onPostExecute(String result) {
        (TextView)findViewById(R.id.Quote).append(result).append("\"");
    } //  \" makes it put an actual " inside a string
}

旧答案:

我敢打赌,您的堆栈跟踪(这不是错误,因为 oyu 捕获了它,但它在日志中)读取类似于“主线程上的网络”?

因为那是你想要做的事情,而且那是你不被允许做的事情。相反,把它放在一个 AsyncTask 中:

onCreate(){ //beware pseudo code because it doesn't matter
    //do stuff
    setContentView(...); //Above here, everything stays as is.
    //below here, only that:
    new GetQuoteTask.execute();
}

class GetQuoteTask extends AsyncTask<Void, Void, String>{
    String doInBackground(...){ //<- pseudo code, code completion is your friend
        String result = getJson();
        Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
        return result;
    }
    onPostExecute(String result){
        maybePutYourStringSomewhereAKAUpdateUI();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}

【讨论】:

    【解决方案2】:

    在你的代码中

    String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
    

    而你要获取的网址是

    http://quotesondesign.com/api/3.0/api-3.0.json?callback=json
    

    请注意您的代码中有callback=?,而URL 有callback=json

    【讨论】:

    • 既然您有查询,我建议您构建一个 URI。
    • 因为我对 android 编码还很陌生,请告诉我,这个 URI 是什么,我用它做什么?
    • 嗯,在网络库中处理 URI 编码相当疯狂是很常见的。您永远不知道哪种方法正在处理编码字符串或“原始”字符串。为了确保 Android 框架不会弄乱您的字符串,您可以手动构建 URI。 URI 只是一种使用常见的blahblah.com:8080/mypage?k=v#anchor 格式寻址事物的方式。它比这更复杂一些,但你不必担心。请参阅stackoverflow.com/questions/2959316/… 以获得帮助。
    • 我不得不承认,像这样搞乱 URI 通常是一场噩梦。把它想象成一种学习体验,除了痛苦和挫折,你什么都学不到。
    【解决方案3】:

    在 Android 4.2 之后,您无法在 UI 线程(“主”线程)上发出 Http 请求。您需要在单独的线程中执行此操作。

    您可以找到示例 on this website 或在此 stackoverflow 帖子中:HttpClient.execute(HttpPost) on Android 4.2 error

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-27
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多