android使用url connection示例(get和post数据获取返回数据)



// Android 中使用 URLConnection 进行 GET 请求的示例
try {
    URL url = new URL("http://example.com/api/data");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");

    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }

    conn.disconnect();

} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

// Android 中使用 URLConnection 进行 POST 请求的示例
try {
    URL url = new URL("http://example.com/api/data");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty("Content-Type", "application/json");

    try(OutputStream os = conn.getOutputStream()) {
        byte[] input = "{\"key\":\"value\"}".getBytes("utf-8");
        os.write(input, 0, input.length);           
    }

    try(BufferedReader br = new BufferedReader(
            new InputStreamReader(conn.getInputStream(), "utf-8"))) {

        StringBuilder response = new StringBuilder();
        String responseLine = null;
        while ((responseLine = br.readLine()) != null) {
            response.append(responseLine.trim());
        }
        System.out.println(response.toString());
    }

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

上述代码分别展示了在Android环境下如何使用`HttpURLConnection`类来执行GET和POST请求。注意,在实际应用中,可能还需要考虑异常处理、请求超时设置、线程管理等问题。另外,对于网络请求,建议使用Android提供的`Volley`、`Retrofit`等网络请求库,这些库提供了更丰富的功能和更好的封装,使得网络请求更加简便和安全。