Http协议之content

用android 通过http协议提交数据至服务器 content的内容

代码如下:

private static JSONObject connUpload(String baseUrl, Map<String, String> params, String content) throws IOException, JSONException {
        
        String end = "
";
        String hyphens = "--";
        String boundary = UUID.randomUUID().toString().replace("-", "");
        
        //将需求连接转换成实际链接  如加上手机的基本信息等。
        String realUrl = HttpUtil.buildUrl(baseUrl);
        LogUtil.i("realurl:" + realUrl);
        
        URL url = new URL(realUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(TIMEOUT);
        
        //Post 请求不能使用缓存
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("enctype", "multipart/form-data;");
        
        DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
        
        writer.writeBytes("Content-Type: multipart/form-data;boundary=" + boundary + end);
        writer.writeBytes(hyphens + boundary + end);
        
        if(params != null && params.size() > 0) {
            for(String key : params.keySet()) {

                 if(params.get(key) != null) {
                      writer.writeBytes("Content-Disposition: form-data; name=""+ key + """ + end + end);

                      //注意此处不能用writeBytes 不然会出现乱码问题
                      writer.writeUTF(params.get(key));
                      writer.writeBytes(end + hyphens + boundary + end);
                 }

            }
        }

// 构造DataOutputStream流 writer.writeBytes("Content-Disposition: form-data; " + "name="file";filename="" + content + """ + end); writer.writeBytes("Content-Type: multipart/form-data;" + end); writer.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(content); /* 设定每次写入1024bytes */ byte[] buffer = new byte[Constant.NET_BUFF_SIZE]; int length = -1; /* 从文件读取数据到缓冲区 */ while ((length = fStream.read(buffer)) != -1) { writer.write(buffer, 0, length); } writer.writeBytes(end); fStream.close(); writer.writeBytes(hyphens + boundary + hyphens + end); writer.flush(); writer.close(); //, Constant.CHARSET BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); char[] buff = new char[Constant.NET_BUFF_SIZE]; int flag = 0; while((flag = reader.read(buff)) != -1) { sb.append(buff, 0, flag); } reader.close(); conn.disconnect(); LogUtil.i("response:" + sb); return new JSONObject(sb.toString()); }
原文地址:https://www.cnblogs.com/hzm112567/p/3699374.html