HTTP Requests in Glass GDK

青春壹個敷衍的年華 提交于 2019-12-03 08:52:42

You can make any post request like in smartphones, but ensure you make the requests using an AsyncTask.

For example:

private class SendPostTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
            // Make your request POST here. Example:
            myRequestPost();
            return null;
    }

    protected void onPostExecute(Void result) {
      // Do something when finished.
    }
}

And you can call that asynctask anywhere with:

new SendPostTask().execute();

And example of myRequestPost() may be:

private int myRequestPost() {

    int resultCode = 0;

    String url = "http://your-url-here";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add headers you want, example:
    // post.setHeader("Authorization", "YOUR-TOKEN");

    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("id", "111111"));
    nameValuePairs.add(new BasicNameValuePair("otherField", "your-other-data"));

    try {
        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + post.getEntity());
        System.out.println("Response Code : " + 
                                    response.getStatusLine().getStatusCode());

        resultCode = response.getStatusLine().getStatusCode();

        BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));

        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        System.out.println(result.toString());
    } catch (Exception e) {
        Log.e("POST", e.getMessage());
    }

    return resultCode;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!