HttpURLconnection使用POST方式提交JSON数据给服务器

8 篇文章 0 订阅
1 篇文章 0 订阅

HttpURLconnection使用POST方式提交JSON数据给服务器

最原始的味道,使用HttpURLconnection提交JSON数据给后台服务器。此处留下标记。


  • 将javabean对象转换成Json字符串。
  • 通过HttpUrlconnection提交数据。
  • getRequestCode返回415

1.javabean转换成JSON字符串工具类。这里使用Gson解析器,请各位自行添加依赖包。

//将JSON字符串转换成javabean
public static <T> T parsr(String json ,Class<T> tClass){
        //判读字符串是否为空
        if(TextUtils.isEmpty(json)){
            return null;
        }

        if(gson==null){
            gson = new Gson();
        }
        return gson.fromJson(json,tClass);
    }
    //将javabean转换成JSON字符串
    public static String converJavaBeanToJson(Object obj){
        if(obj == null){
            return "";
        }
        if(gson == null){
            gson = new Gson();
        }
        String beanstr = gson.toJson(obj);
        if(!TextUtils.isEmpty(beanstr)){
            return beanstr;
        }
        return "";
    }
  1. HttpUrlconnection部分
//发送JSON字符串 如果成功则返回成功标识。
    public static String doJsonPost(String urlPath, String Json) {
        // HttpClient 6.0被抛弃了
        String result = "";
        BufferedReader reader = null;
        try {
            URL url = new URL(urlPath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
          conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            if (Json != null && !TextUtils.isEmpty(Json)) {
                byte[] writebytes = Json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(Json.getBytes());
                outwritestream.flush();
                outwritestream.close();
                Log.d("hlhupload", "doJsonPost: conn"+conn.getResponseCode());
            }
            if (conn.getResponseCode() == 200) {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

亲测可行,亲们可以多试试。

  • 3
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
,你能给我一个示例代码吗? 当然可以,以下是一个使用HttpURLConnection进行post请求的示例代码: ``` URL apiUrl = new URL("your_api_url_here"); HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection(); // 设置请求类型为POST connection.setRequestMethod("POST"); // 设置请求头 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); // 开启输出流,因为我们要向服务器发送数据 connection.setDoOutput(true); // 构建请求体,这里假设我们要传递一个JSON对象为请求体 JSONObject requestBody = new JSONObject(); requestBody.put("param1", "value1"); requestBody.put("param2", "value2"); String requestBodyString = requestBody.toString(); // 将请求体写入输出流 OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestBodyString); writer.flush(); writer.close(); // 获取接口返回的数据 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream responseStream = connection.getInputStream(); String responseData = convertStreamToString(responseStream); responseStream.close(); // 处理返回的数据 } else { // 接口请求失败,处理异常 } // 关闭连接 connection.disconnect(); ``` 在这个示例中,我们首先构建了一个URL对象,并使用它创建了一个HttpURLConnection对象。接着,我们设置了请求方式POST,并设置了请求头,然后开启了输出流并写入请求体。最后获取接口返回的数据并处理。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

我的兄弟叫顺溜2011

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值