Jersey request.getInputStream() - java

#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);

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

Related

Force java.net.HttpUrlConnection to return GET-response regardless of Http-Status-Code

I'm working on a HTTP-Client to sent GET-Requests to an API, which responds with proper JSON-Objects even when the HTTP-Status Codes contains an Error such as 401.
public String get(String url){
URL target;
HttpURLConnection connection;
int code = 200;
BufferedReader reader;
String inputLine;
String result = null;
try {
target = new URL(url);
} catch (MalformedURLException ex) {
return result;
}
try {
connection = (HttpURLConnection)target.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//code = connection.getResponseCode();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
result = "";
while ((inputLine = reader.readLine()) != null){
result += inputLine;
}
reader.close();
} catch (IOException ex) {
return "...";
}
return result;
}
When that's the case, the IOException is thrown and the response isn't written. However, I want to receive the response regardless of the HTTP-Status-Code and hande error handling myself. How can I achieve this?
I don't believe you can do that, but there's https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html#getErrorStream-- for getting the payload in case of an error.

Send HTTP Post with querystring in URL

I have doubts about send HTTP Post using querystring.
I have the follow code below but thie code not working. I try send by web service the user and password, embedded in URL, but it not working. this code cannot connect on web-service.
#Override
protected String doInBackground(String... params) {
String result = "";
try {
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user="+user+"&senha="+password);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return result;
}
I think you mean GET request not POST,
and you should encode the variables in the query params, "user" and "password" in your case.
URL url = new URL("http://192.168.0.11:8080/api/Usuario/doLogin?user=" + URLEncoder.encode(user, "UTF-8")+"&senha="+ URLEncoder.encode(password, "UTF-8"));

How do I send a request to another domain and get the response body in a Spring MVC controller?

I have some controller and I need to send request to another domain and get response result body (it is every time html). How can I do it? Is HttpURLConnection only solution?
#RequestMapping("/")
public ModelAndView mainPage(){
ModelAndView view = new ModelAndView("main");
String conten = /*Here is request result to another domain(result is just html, not JSON)*/
view.addAttribute("statistic","conten);
return view;
}
Here is an exemple to make a request :
String url = "http://www.google.com/";
URL url= new URL(url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
// Important to be thread-safe
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print html string
System.out.println(response.toString());
For a more simpler way
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(
new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
Good for reading web-services (JSON Response).

Exception calling an URL from a servlet

I'm trying to call an URL (URL contains only json code) from a servlet but I keep getting a read time out exceptions on getInputStream().
public class SimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse esponse) throws IOException, ServletException {
BufferedReader reader = null;
StringBuilder stringBuilder;
InputStream in=null;
String json=null;
URL url = new URL("http://localhost:8080/SimpleWeb/users");
try{
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-type", "application/json");
conn.setReadTimeout(5000);
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
stringBuilder = new StringBuilder();
String line=null;
while((line = reader.readLine()) != null){
stringBuilder.append(line + "\n");
}
json = stringBuilder.toString();
System.out.println(json);
}catch(Exception e){
System.out.println(e);
}finally{
if(reader!=null)
reader.close();
}
}
}
The code works by replacing http://localhost:8080/SimpleWeb/users with http://localhost:8080/SimpleWeb/users.txt(but only when called from a plain java app, not a servlet)
Can anyone help to see what I might be doing wrong?

Catch errors of HttpUrlConnection in AsyncTask

I'm searching for a best practice to handle errors in an HttpURLConnection especially if the host is not available. How did I have to change my source?:
protected String doInBackground(String... strings) {
URL aURL;
String line;
HttpURLConnection connection;
BufferedReader reader;
StringBuilder stringBuilder = null;
try {
aURL = new URL(strings[0]);
connection = (HttpURLConnection) aURL.openConnection();
InputStream aInputStream = connection.getInputStream();
BufferedInputStream aBufferedInputStream = new BufferedInputStream(aInputStream);
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
} catch (IOException e) {
Log.d("svc", e.toString());
}
return stringBuilder.toString();
}
you will get different responsecode using connection.getResponseCode()
Check for the response codes for host not available and you will be set.

Categories