【问题标题】:Android studio parsing json objectAndroid studio解析json对象
【发布时间】:2021-10-30 05:11:57
【问题描述】:

我在 android studio 中的代码有问题。 json 对象的 url 未打开。当我更改 url 以测试我的代码是否有任何问题时,没关系。这两个网址之间的唯一区别是其中一个是https(运行没有任何问题),另一个是http(不起作用)。如何运行代码没有问题?

package com.example.chatbot;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void onClick(View view){
        TextView textView = findViewById(R.id.textView);
        String input = textView.getText().toString();
        //textView.setText(" ");

        TextView out=findViewById(R.id.outPut);

        
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url ="http://api.brainshop.ai/get?bid=159114&key=OCfIpglFJbfXDt2G&uid=[uid]&msg=[msg]=hello";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //set the text
                String res = response.toString();
                Toast.makeText(MainActivity.this,response.toString(),Toast.LENGTH_SHORT).show();
                out.setText(res);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        queue.add(request);
    }


}

【问题讨论】:

  • 您应该在您的onErrorResponse 中添加一些内容,以便您知道是否遇到错误

标签: java android json


【解决方案1】:

您应该在您的 AndroidManifest 文件中将“android:usesCleartextTraffic”标志设置为 true。 由于目标 api 28,它默认为 false。 more info here

【讨论】:

    猜你喜欢
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2016-11-20
    相关资源
    最近更新 更多