Glass GDK中的HTTP请求 [英] HTTP Requests in Glass GDK

查看:83
本文介绍了Glass GDK中的HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现GDK应用程序,并且需要在我的应用程序中执行一些HTTP Post请求.我是否以与Android手机相同的方式发送HTTP请求,或者有其他方法可以发送HTTP请求? (我已经尝试了在手机上使用的代码,但不适用于玻璃.)

I am implementing a GDK application and need to do in my application some HTTP Post requests. Do I send the HTTP requests the same way as on android phone or there is some other way of doing it? (I have tried the code that I am using on my phone and it's not working for glass.)

感谢您的提前帮助.

推荐答案

您可以像在智能手机中一样发出任何发布请求,但请确保使用AsyncTask发出请求.

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

例如:

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.
    }
}

您可以通过以下任何地方调用该asynctask:

And you can call that asynctask anywhere with:

new SendPostTask().execute();

myRequestPost()的示例可能是:

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;
}

这篇关于Glass GDK中的HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆