【发布时间】: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