Android HTTP API 调用

Android HTTP API call

我对 Android Studio 很陌生,我正在尝试使用 api 密钥和应用程序 ID 调用 MVC Api 服务。

但是,每当我尝试使用 api 密钥和应用程序 ID 时,它总是抛出 "Trust anchor for certification path not found.",而当我尝试不使用 api 密钥时它运行良好。

你能给我一个建议吗?谢谢。

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

    Button btn = (Button)findViewById(R.id.button);
    tv = (TextView)findViewById(R.id.textView);

    btn.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v) {
            new JSONTask().execute("");

        }
    });
}

public class JSONTask extends AsyncTask<String, String, String>
{

    @Override
    protected String doInBackground(String... params) {
        try{
            StringBuilder result = new StringBuilder();
            URL url2 = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
            conn.setRequestMethod("GET");

            conn.setRequestProperty("Apikey",key);
            conn.addRequestProperty("AppID",id);

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            rd.close();
            return result.toString();
        }

        catch (IOException e)
        {
            Log.e("MYAPP", "exception", e);
            return "error";
        }

    }
    protected void onPostExecute(String result)
    {
        super.onPostExecute(result);
        tv.setText(result);
    }
}

这种异常主要是由于网络服务配置错误引起的。查看 this 篇文章。它完全描述了为什么你会得到这个例外。