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?
Related
#Override
protected String doInBackground(String... strings) {
String result = HttpRequest.getExecute("http://newsapi.org/v2/everything?q=bitcoin&from=2020-05-30&sortBy=publishedAt&apiKey=myAPIkey");
return result;
}
I am getting a null response on passing this URL even though the same URL when opened on the browser shows a lot of stuff. I am getting a Null Pointer Exception. Please help. Below is my HttpRequest class.
HTTPRequest Class:
public class HttpRequest {
public static String getExecute(String targetUrl)
{
URL url;
HttpURLConnection httpURLConnection = null;
try
{
url = new URL(targetUrl);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
InputStream inputStream;
if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK)
inputStream = httpURLConnection.getErrorStream();
else
inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuffer response = new StringBuffer();
while ( (line = bufferedReader.readLine()) != null)
{
response.append(line);
response.append('\r');
}
bufferedReader.close();
return response.toString();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
finally {
if(httpURLConnection != null)
{
httpURLConnection = null;
}
}
}
}
You have to call connect method before reading the result or response code. Add the below line after setting up the request method
httpURLConnection.connect()
What i want?
I'm developing a Java application using the HttpUrlConnection library to send a POST and return the response from the site.
What is going on?
The code does not display syntax errors but when I execute it, it prints the message "propertyValue: false" even though I have not put any command to print anything.
What i need?
I need to know where this error is (propertyValue: false), because as I said, it does not show as if it had an error.
source:
import java.util.*;
import java.io.*;
import java.net.*;
public class Main
{
public static void main(String[] args) throws IOException
{
String target = "http://google.com";
String parameters = "contentOfPost";
URL url = new URL(target);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
try{
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", parameters + Integer.toString(parameters.getBytes().length));
conn.setRequestProperty("Content-Language", "pt-BR");
conn.setRequestProperty("Referer", "https://www.google.com");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(parameters);
wr.flush();
wr.close();
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line=null;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (IOException e){}
}
}
Out: propertyValue:false
I added this method to my MainActivity.java
But i'm getting error on the static: Inner classes cannot have static declatarions.
protected static String excutePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
java.io.InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new java.io.InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
String line;
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
I can remove the static and then i'm getting no errors.
But where do i call this method from now ? From inside the onCreate ?
Tried but it's not exist when i type excute....in the onCreate it's not exist can't call it.
How do i use this method ? And what should i put as urlParameters ?
The outer class which holds the "excutePost" is an inner class therefore it cannot have static methods in it. What you can do is move the outer class to a separate file and make it non static - this will solve your problem.
#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
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.