Java编写Http的Get和Post请求示例代码

1 篇文章 0 订阅

Get请求

示例代码

		/**
         * 点击事件(Get请求)
         */
        findViewById(R.id.sendGetReq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.e("发送Get请求");
                String result = null; //Get请求返回结果
                String argUrl = "请求url";

                // 需要传给服务端的数据
                Map<String, String> mapData = new HashMap<>();
                mapData.put("张三", "23");
                mapData.put("李四", "24");
                mapData.put("王五", "25");

                try {
                    // 发送Get请求
                    result = HttpUtils.getWithParams(argUrl, mapData, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 拿到返回结果 做业务逻辑处理(json格式)
                JSONObject resultJson = JSONObject.parseObject(result);
                String resultKey = resultJson.getString("需要校验的返回值");
                if (!resultKey.equals("1")) {
                    LogUtil.e("请求失败...");
                    return;
                }
                LogUtil.e("请求成功!");
                return;
            }
        });

HttpUtils

package com.gaojc.text.Utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

	public static String getWithParams(String argUrl, Map<String, String> headers, Map<String, String> params, Proxy proxy) throws IOException {
        String requestUrl = getRequestUrl(argUrl, params);
        return get(requestUrl, headers, proxy);
    }

    public static String getRequestUrl(String url, Map<String, String> params) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(url);
            // 返回指定字符在字符串中第一次出现处的索引位置,如果此字符串中没有这个字符,则返回-1
            if (url.indexOf("&") > 0 || url.indexOf("?") > 0) {
                sb.append("&");
            } else {
                sb.append("?");
            }
            for (Map.Entry<String, String> urlParams : params.entrySet()) {
                String value = urlParams.getValue();
                // 对参数进行utf-8编码
                String urlValue = null;
                if (value != null) {
                    urlValue = URLEncoder.encode(value, "UTF-8");
                }
                sb.append(urlParams.getKey()).append("=").append(urlValue).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }
    
    public static String get(String argUrl, Map<String, String> headers, Proxy proxy) throws IOException {
        LogUtil.e("请求的url是:" + argUrl);
        InputStream is = null; //字节输入流,用来将文件中的数据读取到java程序中
        ByteArrayOutputStream os = null; //byte数组缓冲区,用来捕获内存缓冲区的数据
        HttpURLConnection urlConnection = null; //网络请求连接

        try {
            // 将url转换为URL类对象
            URL url = new URL(argUrl);
            // 打开url连接 得到urlConnection对象
            if (proxy == null){
                urlConnection = (HttpURLConnection) url.openConnection();
            }else {
                urlConnection = (HttpURLConnection) url.openConnection(proxy);
            }

            // 设置连接
            urlConnection.setRequestMethod("GET"); //设置请求方式
            urlConnection.setConnectTimeout(20000); //设置连接超时时间
            urlConnection.setReadTimeout(20000); //设置读取超时时间
            urlConnection.setDoInput(true); //设置是否从HttpURLConnection读入
            urlConnection.setUseCaches(false); //不使用缓存

            // 设置请求头信息
            if (headers != null){
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    urlConnection.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }

            // 连接
            urlConnection.connect();

            // 得到响应码
            int responseCode = urlConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK){
                // 得到响应流
                is = urlConnection.getInputStream();
                os = new ByteArrayOutputStream();
                // 创建字节数组 用于缓存
                byte[] tmp = new byte[1024];
                // 将内容读到tmp中 读到末尾为-1
                int i = is.read(tmp);
                while (i > 0){
                    os.write(tmp,0,i);
                    i = is.read(tmp);
                }
                // 获取内存缓冲区的数据
                byte[] bs = os.toByteArray();
                // 转换为字符串
                return new String(bs);
            }
            // 抛出错误状态码
            throw new IOException("responseCode:" + responseCode);
        } catch (Exception e) {
            // 抛出错误信息
            throw e;
        }finally {
            // 关闭资源
            if (is != null){
                is.close();
            }
            if (os != null){
                os.close();
            }
            if (urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }

}

Post请求

示例代码

		/**
         * 假设点击事件(Post请求)
         */
        findViewById(R.id.sendPostReq).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.e("发送Post请求...");
                String result = null; //Post请求返回结果
                String argUrl = "请求url";
                /**
                 * 这里数据一般都是JSON
                 *  所在app的 build.gradle 里面引用JSONObject类:api 'com.alibaba:fastjson:1.2.76'
                 *  JSON数据转为String类型传递即可
                 */
                // 需要传给服务端的数据
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("张三", "23");
                jsonObject.put("李四", "24");
                jsonObject.put("王五", "25");

                String param = jsonObject.toJSONString();
                try {
                    // 发送post请求
                    result = HttpUtils.postWithJson(argUrl, null, param, null);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 对结果进行处理
                JSONObject resultJsonObject = null;
                resultJsonObject = JSONObject.parseObject(result);
                // 获取key属性的值 后续做业务逻辑处理
                String value = resultJsonObject.getString("key");
                if (!value.equals("1")) {
                    LogUtil.e("请求失败");
                    return;
                }
                // 继续走业务
                LogUtil.e("请求成功");
                return;
            }
        });

HttpUtils

package com.gaojc.text.Utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {

    public static String postWithJson(String argUrl, Map<String, String> headers, String jsonStr, Proxy proxy) throws IOException {
        if (headers == null) {
            headers = new HashMap<>();
        }
        headers.put("Content-Type", "application/json"); //发送数据类型
        headers.put("Charset", "UTF-8"); //发送请求编码类型
        headers.put("Connection", "Close"); //不使用长链接
        return post(argUrl, headers, jsonStr, proxy);
    }

    public static String post(String argUrl, Map<String, String> headers, String postData, Proxy proxy) throws IOException {
        InputStream is = null; //字节输入流,用来将文件中的数据读取到java程序中
        BufferedWriter writer = null; //字符缓冲输出流,将文本写入字符输出流,缓冲字符
        ByteArrayOutputStream os = null; //byte数组缓冲区,用来捕获内存缓冲区的数据
        HttpURLConnection connection = null; //网络请求连接

        try {
            // 将url转换为URL类对象
            URL url = new URL(argUrl);
            // 打开url连接
            if (proxy == null) {
                connection = (HttpURLConnection) url.openConnection();
            } else {
                connection = (HttpURLConnection) url.openConnection(proxy);
            }
            // 连接设置
            connection.setRequestMethod("POST"); //设定请求的方法为POST,默认是GET
            connection.setConnectTimeout(20000); //设置连接主机超时(单位:毫秒)
            connection.setReadTimeout(20000); //设置从主机读取数据超时(单位:毫秒)
            connection.setDoOutput(true); //设置是否向HttpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            connection.setDoInput(true); //设置是否从HttpUrlConnection读入,默认情况下是true;
            connection.setUseCaches(false); //Post请求不能使用缓存

            // 设置请求头信息
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 连接
            connection.connect();

            // 向字符缓冲流写入数据
            if (postData != null) {
                writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
                writer.write(postData);
                writer.close();
            }

            // 得到响应码
            int responseCode = connection.getResponseCode();

            // 请求成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 得到响应流
                is = connection.getInputStream();
                os = new ByteArrayOutputStream();
                // 创建字节数组 用于缓存
                byte[] tmp = new byte[1024];
                // 将内容读到tmp中 读到末尾为-1
                int i = is.read(tmp);
                while (i > 0) {
                    os.write(tmp, 0, i);
                    i = is.read(tmp);
                }
                // 获取内存缓冲区的数据
                byte[] bs = os.toByteArray();
                // 转换为字符串
                return new String(bs);
            }
            // 抛出错误状态码
            throw new IOException("responseCode:" + responseCode);
        } catch (Exception e) {
            // 抛出错误信息
            throw e;
        } finally {
            // 关闭资源
            if (is != null)
                is.close();
            if (writer != null)
                writer.close();
            if (os != null)
                os.close();
            if (connection != null)
                connection.disconnect();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { 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(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { 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(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是阿超

现在二师兄的肉比师父的都贵了.

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值