Calling web API and Receive return value in Android

后端 未结 4 1423
花落未央
花落未央 2021-01-03 15:45

I\'ve googled for that topics and don\'t get any useful information.

I want to use Web API in my android projects, but don\'t know how to call them from android or j

4条回答
  •  没有蜡笔的小新
    2021-01-03 16:23

    Since I just want to display the the User ID return from the API, below the solution is work for me.

    public class MainActivity extends Activity {
    
        public static TextView txtUserid;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
                        Button btnUserid = (Button) findViewById(R.id.btnUserid);
            btnUserid.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    new UserNameToId().execute("https://uhunt.onlinejudge.org/api/uname2uid/almaruf");
                }
            });
        }
    
        protected class UserNameToId extends AsyncTask {
            @Override
            public String doInBackground(String... url) {
    
                try {
                    URL Url = new URL(url[0]);
                    URLConnection urlConnection = Url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    String str = "";
                    str = bufferedReader.readLine();
                    return str;
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                return null;
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                txtUserid = (TextView) findViewById(R.id.txtUserId);
                txtUserid.setText(result);
            }
        }
    }
    

提交回复
热议问题