Java PostData和MultiForm

时间:2014-07-24 09:33:03

标签: http-post multipartform-data multipartentity

我正在尝试将一些数据发布到服务器但未按预期获得结果。 我得到200 OK响应,但返回的html源代码有一个字符串说 "错误 - 找不到404页面"

我认为我对我发送的数据集做错了。 也许我错过了一些东西,因为我之前从未使用过多种数据。

以下是发送的多种数据(我已使用篡改数据检查发送的内容

    POSTDATA =-----------------------------124853047628807
Content-Disposition: form-data; name="mgnlModelExecutionUUID"

4ee01e05-dc16-4535-a222-693b98ec9b69
-----------------------------124853047628807
Content-Disposition: form-data; name="field"


-----------------------------124853047628807
Content-Disposition: form-data; name="name"

test
-----------------------------124853047628807
Content-Disposition: form-data; name="surname"

test
-----------------------------124853047628807
Content-Disposition: form-data; name="age"

test
-----------------------------124853047628807--

为了发送这些数据,我所做的是创建一个如下所示的MultipartEntityBuilder:

    StringBody name = new StringBody("test", ContentType.MULTIPART_FORM_DATA);
    StringBody surname = new StringBody("test", ContentType.MULTIPART_FORM_DATA);
    StringBody age = new StringBody("test", ContentType.MULTIPART_FORM_DATA);
    StringBody field = new StringBody("", ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("name", name);
    builder.addPart("surname", surname);
    builder.addPart("age", age);
    builder.addPart("field",field);


    return builder;

最重要的是,我发送的标题如下:

 post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0");
        post.addHeader("Accept", "text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8");

我尝试设置multiform标头,但它不起作用

post.addHeader("Content-type", "multipart/form-data");

关于我可能遗失的任何建议? 谢谢你

3 个答案:

答案 0 :(得分:0)

我知道我使用我编写的代码时遇到问题,以便发布一些文本和一些二进制文件,最后自己编写整个应用程序/多部分文件。

HttpURLConnection conn =(HttpURLConnection)url.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundry);
        conn.setRequestProperty("Authorization", "----------------------------");



        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"user_id\""+lineend+lineend);
        out.writeBytes("1"+lineend);

        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"preview_id\""+lineend+lineend);
        out.writeBytes("1"+lineend);

        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"categories_id\""+lineend+lineend);
        out.writeBytes("2"+lineend);

        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"title\""+lineend+lineend);
        out.writeBytes("Mama"+lineend);

        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"tags\""+lineend+lineend);
        out.writeBytes("mama"+lineend);


        out.flush();


        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"video\"; filename=\""+file.getName()+"\""+lineend);
        out.writeBytes(lineend);
        Log.d("UPLOAD", "Titlul video-ului ="+file.getName());



        //decoding of bytes from video
        FileInputStream file_stream = new FileInputStream(file);
        bytesAvailable =file_stream.available();
        bufferSize = Math.min(bytesAvailable,maxBufferSize);
        buffer = new byte[bufferSize];
        Log.d("UPLOAD", "Bytes Read Video =" +bytesRead);

        bytesRead = file_stream.read(buffer);
        //writting to outputstream
        while (bytesRead >0){
            out.write(buffer, 0, bytesRead);
            bytesRead=file_stream.read(buffer);

        }
        Log.d("UPLOAD", "Done Loading first buffer");

        file_stream.close();

        out.writeBytes(twoHiphens+boundry+lineend);
        out.writeBytes("Content-Disposition: form-data; name=\"thumb\"; filename=\""+image.getName()+"\""+lineend);
        out.writeBytes(lineend);
        Log.d("UPLOAD", "Titlul preview-ului ="+image.getName());

        //decodint image bytes
        FileInputStream image_stream = new FileInputStream(image);
        int bytesRead2;
        int bytesAvailable2, bufferSize2 ;
        bytesAvailable2 = image_stream.available();
        bufferSize2 = Math.min(bytesAvailable2, maxBufferSize);
        byte []buffer2 = new byte[bufferSize2];


        //writing to outputstream
        bytesRead2 = image_stream.read(buffer2);
        while(bytesRead2>0){
            out.write(buffer2, 0, bytesRead2); //                   bytesAvailable2 = image_stream.available();
            bytesRead2 = image_stream.read(buffer2);
        }
        image_stream.close();

        Log.d("UPLOAD", "Done loading the second buffer");

        out.writeBytes(twoHiphens+boundry+twoHiphens+lineend);
        out.writeBytes(lineend);

        out.flush();
        out.close();



        Log.d("UPLOAD","Response Code = "+conn.getResponseCode());
        String responseMessage = conn.getResponseMessage();
        Log.d("UPLOAD", "Response Message  = "+responseMessage);


        InputStream  in;
        if(conn.getResponseCode() >= 400){
            in = conn.getErrorStream();
            }else{
                in = conn.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
            StringBuilder response = new StringBuilder();
            char []bytes = new char[512];
            int read ;
            while((read = reader.read(bytes))!=-1){
                response.append(bytes, 0, read);
            }

            Log.d("UPLOAD", "Response " +response);


            conn.disconnect();

您可以省略引用二进制数据的代码。希望它会给你一些帮助

答案 1 :(得分:0)

每个StringBody的内容类型可能不一定是ContentType.MULTIPART_FORM_DATA。也许应该是“text / plain”

答案 2 :(得分:0)

试试这个!

        File file = new File(path);


        File image = new File("/storage/emulated/0/DCIM/100MEDIA/a_thumbnail.jpg");
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urls[0]);
        HttpResponse response = null ;
        post.setHeader("Authorization","----------------------------");





        MultipartEntity ent = new MultipartEntity();
        try {

            ent.addPart("user_id",new StringBody("1"));
            ent.addPart("categories_id",new StringBody("3"));
            ent.addPart("tags",new StringBody("mama"));
            ent.addPart("title",new StringBody("mama"));
            ent.addPart("preview_id",new StringBody("2"));
            ent.addPart("thumb", new FileBody(image));
            ent.addPart("video", new FileBody(file));


            post.setEntity(ent);

            response = client.execute(post);

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            answer= answer+bufferedReader.readLine();

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return answer;
    }