标签:android com http blog style class div img code java size
用android 通过http协议提交数据至服务器 content的内容
代码如下:
private static JSONObject connUpload(String baseUrl, Map<String, String> params, String content) throws IOException, JSONException { String end = "\r\n"; 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); StringBuilder sb = new StringBuilder(); // sb.append("&userDto.chatMessage.receiver=" + msg.getReceiver()); // sb.append("&userDto.chatMessage.type=" + msg.getType()); 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()) { sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(end).append(end).append(params.get(key)).append(end + hyphens).append(boundary).append(end); } } writer.writeBytes(sb.toString()); // 构造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) { /* 将数据写入DataOutputStream中 */ LogUtil.i("stream: "+length); 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()); }
Http协议之content,码迷,mamicode.com
标签:android com http blog style class div img code java size
原文地址:http://www.cnblogs.com/hzm112567/p/3699374.html