如何在Android中发起HTTP GET请求

7
我是一名新手,正在学习Android。我想知道如何发送HTTP GET请求,例如:
```

我是新手,请问如何在Android中发送HTTP GET请求?

```
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_token="nnch734d00sl2jdk",
    oauth_nonce="kllo9940pd9333jh",
    oauth_timestamp="1191242096",
    oauth_signature_method="HMAC-SHA1",
    oauth_version="1.0",
    oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"

在Android(Java)中?

4
我相信这个链接能够给你答案:https://dev59.com/NnA75IYBdhLWcg3wB0ZP。 - DRAX
但是我应该把所有参数放在哪里,比如oauth_consumer_key等等... - Amel Jose
这是一个关于OAuth的入门指南 -> https://dev59.com/AXI95IYBdhLWcg3wyRM0 - D-32
从我给出的链接中,尝试操作“response”变量(我没有测试过,但我相信应该有这个选项)。 - DRAX
1个回答

15

如果你之前在普通的Java中做过这个,那么你需要熟悉Android中的InputStreams和OutputStreams。你需要用请求属性“GET”打开连接,然后将参数写入输出流并通过输入流读取响应。你可以在下面的代码中看到:

        try {
        URL url = null;
        String response = null;
        String parameters = "param1=value1&param2=value2";
        url = new URL("http://www.somedomain.com/sendGetData.php");
        //create the connection
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        //set the request method to GET
        connection.setRequestMethod("GET");
        //get the output stream from the connection you created
        request = new OutputStreamWriter(connection.getOutputStream());
        //write your data to the ouputstream
        request.write(parameters);
        request.flush();
        request.close();
        String line = "";
        //create your inputsream
        InputStreamReader isr = new InputStreamReader(
                connection.getInputStream());
        //read in the data from input stream, this can be done a variety of ways
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        //get the string version of the response data
        response = sb.toString();
        //do what you want with the data now

        //always remember to close your input and output streams 
        isr.close();
        reader.close();
    } catch (IOException e) {
        Log.e("HTTP GET:", e.toString());
    }

1
只需不要忘记导入很多内容和声明两个变量。 - Roman Susi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接