在Android中调用Web API并接收返回值

时间:2016-01-21 06:27:55

标签: android api

我已经搜索了这些主题,但没有获得任何有用的信息。

我想在我的android项目中使用Web API,但不知道如何从android或java中调用它们

我从this网站获得了一些WEB API,并希望在我的android项目中使用。 例如,网络API URL : /api/uname2uid/{uname}.

用户名转换为用户数字ID

我想将该API返回的用户ID 显示为TextView。所以我需要返回值作为字符串或数字。请帮助我。

修改
我只是想学习如何使用WEB API
更简单: 在我的计划中,我有一个TextView,一个EditText和一个Button 当我按Button时,TextView将根据EditText字段中提供的用户名的相应用户ID 进行更新。一个工作的例子对我理解这一点很有帮助。

4 个答案:

答案 0 :(得分:2)

一个简单的异步调用可以帮到你。

MainActivity.java

new YourAsync(){

            protected void onPostExecute(Object[] result) {

                String response = result[1].toString();
                try{
                JSONObject jsonObject=(new JSONObject(jsonResult)).getJSONObject("data"); //Parsing json object named 'data'
                yourTextView.setText(jsonObject.getString("uname")); 
        }.execute(YourURL);

YourAsync.java

public class YourAsync extends AsyncTask<String, Integer, Object[]> {

    @Override
    protected Object[] doInBackground(String... params) {
        // TODO Auto-generated method stub

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(params[0].toString());
        Log.d("http client post set","");

        try{
            HttpResponse response = httpclient.execute(httppost);
            Log.d("YourAsync","Executed");
            return new Object[]{response, new BasicResponseHandler().handleResponse(response)};
        }catch(Exception e){
            Log.d("" + e, "");
        }
        return new Object[0];
    }

答案 1 :(得分:0)

您需要AsyncTask使用适当的Connection类进行网络传输和接收,最后通过onPostExecute()将值返回到主UI线程。我真的不确定阻碍你正常进行的关键点是什么。

答案 2 :(得分:0)

public class JsonWebServiceCall {
// HttpURLConnection method to get JSON data from Webservice
public static String GetJsonString(String mUpdateUrl) {

    String result=null;
    try {

        URL url = new URL(mUpdateUrl);

        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        StringBuilder sb = new StringBuilder();

        con.setAllowUserInteraction(false);
        con.setInstanceFollowRedirects(true);
        // con.setRequestMethod("POST");
        con.connect();
         if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // BufferedReader bufferedReader = new BufferedReader(new
        // InputStreamReader(con.getInputStream()));
        try {
            InputStream in = new BufferedInputStream(con.getInputStream());

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(in));

            String json;

            while ((json = bufferedReader.readLine()) != null) {
                System.out.println(mUpdateUrl + "kkkkkkkkk------" + json);
                sb.append(json + "\n");
            }
        } catch (Exception e) {

            e.printStackTrace();

        }
        Log.i("json", "===" + sb.toString().trim());
        result=sb.toString().trim();}
         else{
             result=null;
         }
 return result;
    } catch (Exception e) {
        return null;
    }

}

// HttpURLConnection method to get JSON data from Webservice
public static String PostJsonString(String mUpdateUrl, String webserviceurl) {

    // BufferedReader bufferedReader = null;
    try {

        String urlParameters = mUpdateUrl;
        URL url = new URL(webserviceurl);
        URLConnection conn = url.openConnection();
        StringBuilder sb = new StringBuilder();
        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(
                conn.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));

        while ((line = reader.readLine()) != null) {
            System.out.println(line);
            sb.append(line + "\n");
        }
        writer.close();
        reader.close();
        return sb.toString().trim();
    } catch (Exception e) {
        return null;
    }

}

Asynchtask ..........

public static class AsyncCriticalMessage extends AsyncTask<Void, Void, Void> {

    String result = null;
    CriticalMessageServiceSuccess criticalMessageServiceSuccess = null;

    public AsyncCriticalMessage(CriticalMessageServiceSuccess criticalMessageServiceSuccess) {
        this.criticalMessageServiceSuccess = criticalMessageServiceSuccess;
    }

    @Override
    protected Void doInBackground(Void... params) {
        result = JsonWebServiceCall.GetJsonString(Globals.FORCEUPDATE_MESSAGE_SERVICE_URL);
        return null;
    }

    @Override
    protected void onPostExecute(Void Result) {
        super.onPostExecute(Result);

        criticalMessageServiceSuccess.onSuccess(result);
    }
}
 AsyncCriticalMessage asyncCriticalMessage=new AsyncCriticalMessage(this);
    asyncCriticalMessage.execute();

答案 3 :(得分:0)

由于我只想显示API的 User ID 返回,因此下面的解决方案对我来说是可行的。

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<String, Void, String> {
        @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);
        }
    }
}