HTTP_POST body

首先,一个POSTbody包括如下结构:

Content-Type: multipart/form-data; boundary=-------------------56012339215759
Content-Length: 49387 

-------------------56012339215759
Content-Disposition: form-data; name="text"

微博内容
-------------------56012339215759
Content-Disposition: form-data; name="pic"; filename="MBlog.JPG"
Content-Type: image/jpeg

图片二进制流
-------------------56012339215759

 

这是一个标准的POSTbody的样例,不要忽视其中的回车符和换行符。

下面是通过JAVA的HttpURLConnection所实现的一个POST实例的部分代码:

String boundary = "---------------------------37531613912423";
        String content = "--"+boundary+"/r/nContent-Disposition: form-data; name=/"status/"/r/n/r/n";
        String pic = "/r/n--"+boundary+"/r/nContent-Disposition: form-data; name=/"pic/"; filename=/"postpic.jpg/"/r/nContent-Type: image/jpeg/r/n/r/n";
        byte[] end_data = ("/r/n--" + boundary + "--/r/n").getBytes();  
        File f = new File("c://s.jpg");
        FileInputStream stream = new FileInputStream(f);
        byte[] file = new byte[(int)f.length()];
        stream.read(file);
        request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); //设置表单类型和分隔符  
        request.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length+"test".getBytes().length+pic.getBytes().length+f.length()+end_data.length)); //设置内容长度  
        consumer.setAdditionalParameters(para);
        consumer.sign(request);
        OutputStream ot = request.getOutputStream();
        ot.write(content.getBytes());
        ot.write("test".getBytes());
        ot.write(pic.getBytes());
        ot.write(file);
        ot.write(end_data);
        ot.flush();
        ot.close();

你可能感兴趣的:(file,string,byte,stream,java,c)