Reputation: 1119
@POST
@Path("/getphotos")
@Produces(MediaType.TEXT_HTML)
public String getPhotos() throws IOException{
BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
return "ok";
}
The code above is for my server. But in this code, the String "line" has no value.(always) Is there any problem with the code?
client side code
String message = "message";
URL url = new URL(targetURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(message);
Upvotes: 1
Views: 5084
Reputation: 80603
You can manually consume a request's data in Jersey, as long as you have a valid handle to the actual HttpServletRequest
. On a slight side note, keep in mind that you can only consume the request body once:
@Context
private HttpServletRequest request;
@POST
@Path("/")
public Response consumeRequest() {
try {
final BufferedReader rd = new BufferedReader(new InputStreamReader(
request.getInputStream(), "UTF-8"));
String line = null;
final StringBuffer buffer = new StringBuffer(2048);
while ((line = rd.readLine()) != null) {
buffer.append(line);
}
final String data = buffer.toString();
return Response.ok().entity(data).build();
} catch (final Exception e) {
return Response.status(Status.BAD_REQUEST)
.entity("No data supplied").build();
}
}
Side note: Libraries like Apache Commons IO provide robust functions for reading IO data
Upvotes: 2