Android error : MultipartEntity , request sent by

2020-08-12 01:33发布

问题:

I am suppose to send song (mp3/wav) file and some data through secure restful web service. I am using MultipartEntity to make HttpPost request. but When I execute it through HttpClient, the server replies this error

HTTP Status 400 - Bad Request type: Status report message : Bad Request The request sent by the client was syntactically incorrect (Bad Request).

But the service is doing very well if we call it from its Web interface. please help

its the code

HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost();
        try {
            MultipartEntity reqEntity = new MultipartEntity();

            reqEntity.addPart("email", new StringBody("test@testmail.com"));
            reqEntity.addPart("password", new StringBody("123"));
            reqEntity.addPart("title", new StringBody("My new song"));
            reqEntity.addPart("musicData", new FileBody(new File(FilePath))); 

            // FIlePath is path to file and contains correct file location

            postRequest.setEntity(reqEntity);

            postRequest.setURI(new URI(ServiceURL));
            HttpResponse response = httpclient.execute(postRequest);

        } catch (URISyntaxException e) {
            Log.e("URISyntaxException", e.toString());
        } 

I also included apache-mime4j, httpclient, httpcore and httpmime jars for MultipartEntity.

This is HTML page snap for the Service.

回答1:

Try removing the setURI method and passing the URL in when you create your HttpPost object, as follows. This worked for me (more here).

HttpClient httpclient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(ServiceURL);
try {
    MultipartEntity reqEntity = new MultipartEntity();

    reqEntity.addPart("email", new StringBody("test@testmail.com"));
    reqEntity.addPart("password", new StringBody("123"));
    reqEntity.addPart("title", new StringBody("My new song"));
    reqEntity.addPart("musicData", new FileBody(new File(FilePath)));     
    postRequest.setEntity(reqEntity);

    HttpResponse response = httpclient.execute(postRequest);

} catch (URISyntaxException e) {
    Log.e("URISyntaxException", e.toString());
} 


回答2:

It seems header of the request is incorrect, this problem can occur if you use a different Auth protocol or upper/lower case or simply wrong things in header that server side can't handle.



回答3:

Dont waste your time by trying different different combinations.There are some HTTP Request tools available for HTTP with which you can track request and response you are getting.Ex. HTTP Analyzer download trial version

Call URL from your working webinterface , copy request and response then do same with from program the tool is enogh capable to capture your request and response data.

Now compare working and non working request you will surely able to dignose the issue whether it can be header issue or some authentication related issue.