从Android到Jersey Web服务的错误请求

时间:2014-01-19 14:58:00

标签: java android web-services tomcat jersey

当我尝试将图像从Android应用程序上传到webservice时,我得到400:错误的请求。 以下是我的android代码:

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            builder.addTextBody("email", email);
            builder.addTextBody("title", offer.getOfferTitle());
            builder.addTextBody("desc", offer.getOfferDesc());
            Uri uri = Uri.parse(offer.getOfferImage());
            File file = new File(uri.getPath());
            Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
            byte[] byte_arr = stream.toByteArray();

            ByteArrayBody fileBody = new ByteArrayBody(byte_arr,
                    file.getName());

            //ContentResolver cR = getActivity().getContentResolver();
            //String mime = cR.getType(uri);
            builder.addPart("image", fileBody);  

            HttpPost httppost = new HttpPost(URL_ADD_OFFER);

        httppost.setHeader("Content-Type", "multipart/form-data;charset=UTF-8");
        httppost.setHeader("Accept", "application/json");
        httppost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); 
        httppost.setEntity(builder.build());
        HttpResponse response = httpclient.execute(httppost);

        Log.e("test", "SC:" + response.getStatusLine().getStatusCode());

        HttpEntity resEntity = response.getEntity();

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();

        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        Log.e("test", "Response: " + s);
        return s.toString();

以下是Web服务中的POST方法:

  @POST
@Path("/add")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("application/json")
public Response addNew(
        @FormDataParam("title") String offerTitle, 
        @FormDataParam("desc") String offerDesc,
        @FormDataParam("email") String userID,
        @FormDataParam("image") InputStream fileInputStream,
        @FormDataParam("image") FormDataContentDisposition contentDispositionHeader) {
    ServiceResp resp = new ServiceResp();
    String insertTableSQL = "INSERT INTO items"
            + "(id,user_id,title,image,description,status,created) VALUES"
            + "(?,?,?,?,?,?,?)";
    String name = contentDispositionHeader.getFileName();
    String split [] = name.split(".");
   String image =  split[0].hashCode()+"_"+System.currentTimeMillis()+split[split.length - 1];
    try {
        saveFile(fileInputStream,image);
    } catch(Exception e) {
        resp.setResult(false);
        resp.setError(e.getMessage());
        e.printStackTrace(System.err);
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(resp).build());
    }
    PreparedStatement preparedStatement = null;
    Connection connection = null;
    try{
        Class.forName("com.mysql.jdbc.Driver");
        connection = DriverManager.getConnection(
               Conf.DB_CONNECTION_STRING, Conf.DB_USER, Conf.DB_PASS);

        preparedStatement = connection.prepareStatement(insertTableSQL);
        preparedStatement.setString(1,UUID.randomUUID().toString().replace("-", ""));
        preparedStatement.setString(2, userID);
        preparedStatement.setString(3, offerTitle);
        preparedStatement.setString(4, image);
        preparedStatement.setString(5, offerDesc);
        preparedStatement.setString(6, "PENDING");
        preparedStatement.setTimestamp(7, null);

        preparedStatement.executeUpdate();
        resp.setMessage("The Offer "+offerTitle+" has been accepted for "+userID);
        resp.setResult(true);


    }catch(Exception ex){
        resp.setResult(false);
        resp.setError(ex.getMessage());
        resp.setMessage("Could not add new Offer : "+offerTitle);
        ex.printStackTrace(System.err);
        throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(resp).build());
    }finally{
        if(preparedStatement!=null){
            try{ 
                preparedStatement.close();
            }catch(Exception ex) { 
                 ex.printStackTrace(System.err);
            }
        }
        if(connection!=null){
            try{ 
                connection.close();
            }catch(Exception ex) { 
         ex.printStackTrace(System.err);     
            }
        }
    }
    return Response.status(200).entity(resp).build();
}

最后,这是Android客户端中的错误,来自log cat:

01-19 17:30:22.530: E/test(28315): SC:400
01-19 17:30:22.538: E/test(28315): Response: <html><head><title>Apache Tomcat/7.0.34 
-     Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-
serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-
family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} 
H3   {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-
size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-
color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-
color:#525D76;} P {font-family:Tahoma,Arial,sans-
serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color :
black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 400 - Bad 
Request</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p>
<b>message</b> <u>Bad Request</u></p><p><b>description</b> <u>The request sent by the 
client was syntactically incorrect.</u></p><HR size="1" noshade="noshade"><h3>Apache
Tomcat/7.0.34</h3></body></html>
01-19 17:30:22.577: E/Fairdeals(28315): Value <html><head><title>Apache of type 
java.lang.String cannot be converted to JSONObject
....

所以我不知道为什么我从服务器收到Bad请求。此外,我期待JSON格式的响应,但我得到HTML文本。有人请。谢谢。

0 个答案:

没有答案