Reputation: 273
i am getting multipart entity from android client as shown below.
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(
"http://localhost:9090/MBC_WS/rest/network/mobileUserPictureInsert1");
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("message", new StringBody("hi moni"));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
In jersey i am trying to retrieve message but getting only object.the code is:
@Path("/mobileUserPictureInsert1")
@POST
@Consumes("multipart/*")
public String create(MultiPart multiPart){
BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(0).getEntity();
String message = bpe.toString();
here i AM getting some object ony not message value. what mistake i made.pl help me.
Upvotes: 1
Views: 1260
Reputation: 209112
Yes the the right result. toString()
will just use Object.toString()
, which will result in
getClass().getName() + '@' + Integer.toHexString(hashCode())
which is most likely what you're seeing. Unless BodyEntityPart
overrides the toString()
, which it doesn't. You should instead be getting the InputStream
with BodyEntityPart.getInputStream()
. Then you can do whatever with the InputStream
.
A simple example:
@POST
@Consumes("multipart/*")
public String create(MultiPart multiPart) throws Exception {
String message;
try (BodyPartEntity bpe
= (BodyPartEntity) multiPart.getBodyParts().get(0).getEntity()) {
message = getString(bpe.getInputStream());
}
return message;
}
private String getString(InputStream is) throws Exception {
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
String line;
while((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
}
return builder.toString();
}
On another note: You are already using the Jersey multipart support, you can make life easier and just use its annotation support. For instance, you can just do
@POST
@Consumes("multipart/*")
public String create(@FormDataParam("message") String message){
return message;
}
That is much easier. The @FormDataParam("message")
gets the body name that you defined here:
reqEntity.addPart("message", new StringBody("hi moni"));
and converts to to String. As long as there's a MessageBodyReader available for the Content-Type of the body part, it should be able to be auto-converted.
Upvotes: 1