向Android Studio中的API发送GET / POST请求

时间:2016-07-29 12:34:46

标签: android http

我更新了我的表现:

<uses-permission android:name="android.permission.INTERNET" />

并尝试谷歌如何用android发送简单的http get请求,发现了大量不同的答案,其中大部分已经过时使用了脱离方法。

如何将HTTP GET / POST发送到我的API网址,例如http://www.apiawesome.com/getData

我的API在JSON对象中返回JSON数组。

我的代码:

private void loadData()
    {
        URL url = null;
        try {
            url = new URL("http://www.myapi.com/api/loadData");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            readStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }
}

can't resolve method readStream.in()

3 个答案:

答案 0 :(得分:1)

不要使用HttpURLConnection或Volley,Retrofit是可行的方法。现代,高效,易用,快速。它是一颗真正的钻石。

答案 1 :(得分:0)

试试这个,更新了POST代码,并在url中添加params

struct channel

答案 2 :(得分:0)

在Android中发出HTTP请求的最佳方法之一就是使用谷歌自己的Volley库

您可以参考这些来源以了解如何使用该库:

  1. Transmitting Network Data Using Volley
  2. Sending a Simple Request
  3. Android working with Volley Library
  4. Android JSON parsing using Volley
  5. An Introduction to Volley
  6. 除了这些资源外,图书馆使用起来非常简单,网上有大量文档