我正在android studio上创建一个测试应用程序,问题将从包含JSONObject的URL中调用,由于这些API调用是异步发生的,我必须确保我的应用程序正在等待服务器响应回调,下面是我根据一些internet教程创建的解析方法,如果您能帮助我理解应该应用哪些更改将会很好
private void jsonParse(){
final Question[] quest =new Question[10];
String url="https://opentdb.com/api.php?amount=10";
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray ja=response.getJSONArray("results");
for(int i=0;i<3;i++){
JSONObject temp_quest=ja.getJSONObject(i);
String question =temp_quest.getString("question");
String correctanswer=temp_quest.getString("correct_answer");
String incorrectanswer_1=(String)temp_quest.getJSONArray("incorrect_answers").getString(0);
String incorrectanswer_2=(String)temp_quest.getJSONArray("incorrect_answers").getString(1);
String incorrectanswer_3=(String)temp_quest.getJSONArray("incorrect_answers").getString(2);
String[] temp=new String[3];
temp[0]=incorrectanswer_1;
temp[1]=incorrectanswer_2;
temp[2]=incorrectanswer_3;
quest[i]=new Question(question,correctanswer,temp);
mTextViewResult.append(quest[i].getQuestion()+" \n"+ quest[i].getCorrectAnswer()+"\n "+
quest[i].getAnswer(1)+"\n "+quest[i].getAnswer(2)+"\n "+
quest[i].getAnswer(3)+"\n" +quest[i].getAnswer(4)+"\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
我认为您没有使用正确的表单调用服务。
>
您可以使用异步任务
包装原则。混凝土。混凝土;
导入Android.os.AsyncTask; 导入android.util.log;
导入java.io.IOException; 导入java.net.url; 导入java.net.HTTPURLConnection; 导入java.io.BufferedReader; 导入java.io.InputStreamReader;
公共类Post扩展AsynctAsk<;String,Void,String>; {
private InputStreamReader inputStreamReader;
private BufferedReader bufferedReader;
@Override
protected String doInBackground(String... params){
try {
URL obj = new URL(params[0]);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", " ");
con.connect();
inputStreamReader=new InputStreamReader(con.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader.readLine();
}catch(Exception e){
Log.d("Url doInBackground", e.toString());
return null;
} finally {
try {
closeConnection();
} catch(Exception e){
}
}
}
private void closeConnection() {
try {
if(bufferedReader!=null){
bufferedReader.close();
}
if(inputStreamReader!=null){
inputStreamReader.close();
}
}catch(IOException ex){
Log.d("Url disconnect", ex.toString());
}
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
您可以使用改型来调用服务
将实现联系起来
https://programacionymas.com/blog/consumir-una-api-usando-reverfit
我有一个密码可以呼叫服务部
asyn任务