I am opening an HttpURLConnection and with POST method, I am sending a JSON request that I build form another class. The JSON is structured correctly since I have validated it on debugging. The exception is thrown when trying to read the output response given from the server. This is the Error given
java.io.IOException: Server returned HTTP response code: 400 for URL:
However when I manually try to enter the Url from a web browser with a POST method chrome extension. I can view the response and everything works. So I am sure it has something to do with the following code where I make the connection and read/write.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//add request header
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//mapping objects to json
BatchRequest requestParameters = new BatchRequest(o,d);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestParameters);
connection.setDoOutput(true);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
// this is where the program throws the exception
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Both the URL and the JSON request are correct since They work when I try a manual conenction over a browser.
A DataOutputStream is not needed. Just:
OutputStream os = con.getOutputStream();
Related
I have a problem on HttpURLConnection in post method. Everything is working fine on get method however, when I try to use Post method. I'm getting this error message.
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL
Here's my code snippet. I hope you could help me about this.
URL url = new URL(my url/userInfo);
String encoding = Base64.getEncoder().encodeToString(("username:password").getBytes("UTF-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setRequestProperty("Authorization", "Basic " + encoding);
connection.setRequestProperty("x-csrf-token", "fetch");
String csrfToken = connection.getHeaderField("x-csrf-token");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
String output = in.readLine();
in.close();
String content = data // expected data to retrieve
URL url2 = new URL(my URL);//another url to push the data retrieve
HttpURLConnection connection2 = (HttpsURLConnection) url2.openConnection();
connection2.setDoInput(true);
connection2.setDoOutput(true);
connection2.setRequestMethod("POST");
connection2.setRequestProperty("Authorization", "Basic " + encoding);
connection2.setRequestProperty("Accept", "application/json");
connection2.setRequestProperty("x-CSRFToken", csrfToken);
connection2.setRequestProperty("cache-control", "no-cache");
OutputStream os = connection2.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(data);//this is where the data will be pushed
osw.flush();
osw.close();
os.close();
the idea is, we need first to get the x-csrf-token and data from the first link, which is okay. After GET Method execution, the POST method will occur. unfortunately, the post method is not working. I'm getting the error message shown above. By the way, we tried to do a post method in POSTMAN and it' working fine.
Hoping you could help me about this.
Actually there are two POST URLs. First POST url is login as follows and even it contains body as json as follows.
String loginUrl = "http://00.00.00.00:0000/url/vs1/login";
json = `{"email": "qqqq#mail.com", "password": "/JGgdwd6vhsvJJFGDF7ttd="}`
Second POST url without payload as follows.
String SiteLoginUrl = "http://00.00.00.00:0000/url/vs1/site/1/login";
So first, above first url need to login then only i can login to second url.
Hence first URL is logging in successfully but after getting response i need to login for second URL which doesn't consists of payload or json. So after calling second URL with POST is returning 400 error. For second URL i have written code below.
// java HttpURLConnection for POST without json or payload data
String SiteLoginUrl = "http://00.00.00.00:0000/url/vs1/site/1/login";
HttpURLConnection conn = (HttpURLConnection) new URL(SiteLoginUrl).openConnection();
conn.setDoOutput(true);
conn.setUseCaches(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("ContentType","application/json;charset=UTF-8");
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
JSONObject obj = new JSONObject();
wr.writeBytes(obj.toString()); //String Empty Object
wr.flush();
wr.close();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return 1;
} else {
return 0;
}
In POSTMAN i checked it is working fine (returning successful login response) with text {}(String Empty Object) payload.
I am little confused with the below code or behavior of HttpURLConnection class. I have the below code which hits the URL (rest service in .net) and gets the response from it. When I run the code I am getting the response in both Windows and Unix environment. I have access to this URL.
When I provided the same code to someone who don't have access to the URL, it throws 401 Unauthorized error. But in below code I didn't pass my credentials, how does it automatically validates my credentials ? Is it working for me because HttpURLConnection sets Windows authentication in background in request ?
URL url = new URL(URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setDoOutput(true);
BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
I have returning response to client as
return Response.status(200).entity("Data was succesfully loaded into database").build();
I have to read this on client my client code
URL url=new URL(urlString);
// URLConnection connection=url.openConnection();
//connection.setDoOutput(true);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type",
"application/json");
how to read these type of responses on client side
Once you have HttpURLConnection you can send data to the server (if this is needed, but looks like as it is, because you have POST request):
DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(yourData);
wr.flush();
wr.close();
Then you can check for response code (for e.g. if it is 200):
int responseCode = httpCon.getResponseCode();
And read data from response:
BufferedReader in = new BufferedReader(
new InputStreamReader(httpCon.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
If you want to parse JSON you can use org.json or Gson.
I am trying to send an HTTP POST Request to a remote server using an instance of the HttpURLConnection class. Although, I am able to get a response code and a response message, when I try to write the input stream into a StringBuffer, I am not able to actually read any lines.
When I analyzed the packets sent from WireShark, I noticed that a full response was being sent from the remote server. My only guess as to why I am not able to see it in the Java program is because the time in which I try to read from the InputStream is too late.
So, how do I read the immediate, full response from the remote server using my HttpURLConnection object? Below is the code that I am using:
HttpURLConnection conn = null;
String urlStr = "...";
URL url = null;
try
{
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
...
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
...
}...
Okay, never mind. It turns out that what I was looking for was in the HTTP Respone's header. So, I got what I needed by looking through its headers. ::Face Palm::