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

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;
    }

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

已标记关键词 清除标记
相关推荐
<div class="post-text" itemprop="text"> <p>I am trying to send json data to server using HTTPURLConnection. But every time response id null from server. i tried by POSter also but it is working there. </p> <pre><code> try { jsondata ="{\"A\":\"1234\",\"country_code\":\"91\",\"name\":\"sajal\",\"phone_number\":\"88999\"}"; URL url = new URL(uri); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setConnectTimeout(3000); httpConn.setDoInput(true); httpConn.setDoOutput(true); httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); httpConn.setRequestMethod("POST"); StringBuffer requestParams = new StringBuffer(); if (jsondata != null && jsondata.length() > 0) { Uri.Builder builder = new Uri.Builder().appendQueryParameter("data", jsondata); String query = builder.build().getEncodedQuery(); OutputStream os = httpConn.getOutputStream(); BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); bufferedWriter.write(query); bufferedWriter.flush(); bufferedWriter.close(); os.close(); } InputStream inputStream = null; if (httpConn != null) { inputStream = httpConn.getInputStream(); } else { throw new IOException("Connection is not established."); } BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); response = reader.readLine(); reader.close(); if (httpConn != null) httpConn.disconnect(); } catch (UnknownHostException one) { return response; } catch (SocketException two) { return response; } catch (Exception three) { return response; } return response; } </code></pre> <p>Keeping my json string in "data" key</p> <p>PHP:-</p> <pre><code> if (isset($_POST['data'])) { $data = json_decode($_POST["data"], true); // php code..... } else { // control comes here.. // php code..... } </code></pre> <p>Here $_POST['data'] is not working. Please check whats wrong in PHP or Andooid code. </p> </div>
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页