Content-Type: text/plaincharset=UTF-8
Content-Transfer-Encoding: 8bit
文件参数:
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
参数实体的最后一行是: --加上boundary加上--,最后换行,这里的 格式即为: --OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp--。
模拟文件上传请求
public static void uploadFile(String fileName) {
try {
// 换行符
final String newLine = "\r\n"
final String boundaryPrefix = "--"
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9"
// 服务器的域名
URL url = new URL("www.myhost.com")
HttpURLConnection conn = (HttpURLConnection) url.openConnection()
// 设置为POST情
conn.setRequestMethod("POST")
// 发送POST请求必须设置如下两行
conn.setDoOutput(true)
conn.setDoInput(true)
conn.setUseCaches(false)
// 设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive")
conn.setRequestProperty("Charsert", "UTF-8")
conn.setRequestProperty("Content-Type", "multipart/form-databoundary=" + BOUNDARY)
OutputStream out = new DataOutputStream(conn.getOutputStream())
// 上传文件
File file = new File(fileName)
StringBuilder sb = new StringBuilder()
sb.append(boundaryPrefix)
sb.append(BOUNDARY)
sb.append(newLine)
// 文件参数,photo参数名可以随意修改
sb.append("Content-Disposition: form-dataname=\"photo\"filename=\"" + fileName
+ "\"" + newLine)
sb.append("Content-Type:application/octet-stream")
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine)
sb.append(newLine)
// 将参数头的数据写入到输出流中
out.write(sb.toString().getBytes())
// 数据输入流,用于读取文件数据
DataInputStream in = new DataInputStream(new FileInputStream(
file))
byte[] bufferOut = new byte[1024]
int bytes = 0
// 每次读1KB数据,并且将文件数据写入到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes)
}
// 最后添加换行
out.write(newLine.getBytes())
in.close()
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
.getBytes()
// 写上结尾标识
out.write(end_data)
out.flush()
out.close()
// 定义BufferedReader输入流来读取URL的响应
// BufferedReader reader = new BufferedReader(new InputStreamReader(
// conn.getInputStream()))
// String line = null
// while ((line = reader.readLine()) != null) {
// System.out.println(line)
// }
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e)
e.printStackTrace()
}
}
很简单的, 首先使用io框架, netty, mina 都行。打开socket , 就可以收发数据了。
接来下选择序列化框架,这取决于你的协议类型。文本协议? 字节协议?
文本协议: 比如 json? 那就用fast-json,jackson等来讲对象序列化和反序列化。
字节协议:使用 magic-bytejava-struct之类的框架来进行序列化和反序列化。
能传输, 能序列化/反序列化。 OKK 问题全部解决。 哈哈哈