Receiving null Value while using POST method in servlet? - java

I want to send a string by using POST method in servlet so that it can communicate with other servlet application present in other domain. But I am receiving null in my Input steam object.
My Code:
String content = "10 141 nahush123 01";
URL url = new URL("http://52.220.37.12:8080/servers/servers");
System.out.println(url.toString());
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
OutputStream os = httpCon.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
out.write(content);
//br = BufferReader(out);
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
writer.println(httpCon.getResponseMessage());
httpCon.connect();
br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//reading response
//String resp;
//if(br != null){
content = br.readLine();
//}
System.out.println(content);
writer.println(content);
out.flush();
writer.flush();
writer.close();
out.close();
os.close();

Copy pasted your code in my servlet worked fine
Check that you overrided doPost method in the servlet
Check that you that your post metod work fine and return value, I use "DHC Rest Client" plugin for chrome. It is very cool tool
Try to remove httpCon.connect() line. It is not necessary.
From oracle docs about connect() method:
Operations that depend on being connected, like getContentLength, will
implicitly perform the connection, if necessary.
Operations getResponseMessage, getResponseCode perform the connection.
UPDATED
I tried to test with my local test url and it works. Then i tried with your url and it does not work.
You need to flush output stream before use input stream.
This code work and return "0#5#26#Temperature#Living_Room#555555581#0+0#7#0#Room1#Master_bedroom#555555581#1+1#7#0#Door1#Living_Room#555555581#2+1#6#0#frontdoor#Living_Room#555555581#2+0#6#0#doorback#Balcony#555555581#2+"
PrintWriter writer = res.getWriter();
String content = "10 141 nahush123 01";
URL url = new URL("http://52.220.37.12:8080/servers/servers");
System.out.println(url.toString());
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
httpCon.setDoInput(true);
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
httpCon.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
OutputStream os = httpCon.getOutputStream();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
out.write(content);
out.flush();
//br = BufferReader(out);
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
writer.println(httpCon.getResponseMessage());
//httpCon.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
//reading response
//String resp;
//if(br != null){
content = br.readLine();
//}
System.out.println(content);
writer.println(content);
writer.flush();
writer.close();
out.close();
os.close();

Try with getparameter() function in the servlet

Call this method with your pass string parameter:
public String postData(String reqStr) {
ObjectOutputStream objOS = null;
ObjectInputStream objIS = null;
HttpURLConnection servletCon = null;
try {
if (reqStr != null) {
Thread.sleep(1000);
objOS.writeObject(reqStr);
} else {
throw new Exception("request is null.");
}
} catch (Exception ex) {
logger.error("Failed to send request to server.", ex);
}
String response = null;
try {
objIS = new ObjectInputStream(servletCon.getInputStream());
response = (String) objIS.readObject();
} catch (Exception ex) {
logger.error("Failed to get response from server.", ex);
response = null;
}
return response;
}
Initializing Connection like you but calling differently:
public void initializeUrlConnection(String servletURL, String contentType, String method) {
try {
logger.debug("Servlet URL " + servletURL);
url = new URL(servletURL);
servletCon = (HttpURLConnection) url.openConnection();
servletCon.setUseCaches(false);
servletCon.setDefaultUseCaches(false);
servletCon.setDoInput(true);
servletCon.setDoOutput(true);
servletCon.setRequestProperty("Content-Type", contentType);
servletCon.setRequestMethod(method);
objOS = new ObjectOutputStream(servletCon.getOutputStream());
} catch (IOException ex) {
logger.error("Failed to initialize Http Connection.", ex);
}
}
First of call initialize connection method with required parameter:
Object.initializeUrlConnection(url, contentType,method);
then call posDataMethod with your string/json parameter:
Object.postData(str);

Related

POST JSON to Server and Receive Response

I have a class, called FindMeARestaurantDAO, which contains methods that will make network calls to a server with AsyncTask inner classes in my Activity. I am having issues with my POST request Method, which is as follows:
#Override
public String findMeARestaurant(List<CheckboxDTO> filters) {
String inputLine;
String errors;
String result;
try
{
// For each CheckboxDTO, get the Id and add it to JSONArray
JSONArray checkboxJSONArray = new JSONArray();
for (CheckboxDTO checkbox : filters)
{
try
{
// Create JSONObject
JSONObject object = new JSONObject();
// Build the object
object.put("id", checkbox.getId());
// Add object to JSONArray
checkboxJSONArray.put(object);
}
catch (Exception e)
{
e.printStackTrace();
}
}
// Put JSONArray into wrapping JSONObject
JSONObject serverObject = new JSONObject();
try
{
// Create wrapping JSONObject
serverObject.put("filtersIds", checkboxJSONArray);
}
catch (Exception e)
{
e.printStackTrace();
}
// Create URL object to hold URL
URL findMeARestaurantURL = new URL(findMeARestaurantsURL);
// Create connection to server
HttpURLConnection connection = (HttpURLConnection) findMeARestaurantURL.openConnection();
// Set request method and timeouts
connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.setDoOutput(true);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
// Connect to server
connection.connect();
// Create Writer
Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.write(String.valueOf(serverObject));
// Close Writer
writer.close();
// Create InputStreamReader to read response from server
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
// Create BufferedReader to read through InputStream
BufferedReader reader = new BufferedReader(streamReader);
// Create StringBuilder to hold our result
StringBuilder stringBuilder = new StringBuilder();
// Check if the line read is null
while ((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
// Close out InputStream and BufferedReader
reader.close();
streamReader.close();
// Set result to stringBuilder
result = stringBuilder.toString();
connection.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return result;
}
The method is POST and it appears to send the JSON serverObject to the server when I run my application, but it fails on the InputStreamReader and returns a FileNotFoundException. The server was set up by a partner for this project and says this portion of the API should be working. Am I missing something for the POST request? Do I need to be doing something differently for reading the server's response? Any help would be greatly appreciated.
The solution to this issue was in how I sent the data to the server in a POST request. I had to send my filters' Ids to the server by adding them to my URL before establishing the connection. My modified method iterates through each CheckboxDTO and catches the Id, then adds it to an array, which is then added to the URL:
#Override
public String findMeARestaurant(List<CheckboxDTO> filters) {
String inputLine;
String result;
try
{
// For each CheckboxDTO, get the Id and add it to String Array
int checkboxArray[] = new int[filters.size()];
int i = 0;
for (CheckboxDTO checkbox : filters)
{
try
{
int id = checkbox.getId();
checkboxArray[i] = id;
i++;
}
catch (Exception e)
{
e.printStackTrace();
}
}
// Add filters to end of URL for POST Request
findMeARestaurantsURL += "?filterIds=";
for (i = 0; i < checkboxArray.length; i++)
{
if (i+1 != checkboxArray.length)
{
findMeARestaurantsURL += checkboxArray[i] + ",";
}
else
{
findMeARestaurantsURL += checkboxArray[i];
}
}
// Create URL object to hold URL
URL findMeARestaurantURL = new URL(findMeARestaurantsURL);
// Create connection to server
HttpURLConnection connection = (HttpURLConnection) findMeARestaurantURL.openConnection();
// Set request method and timeouts
connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.setDoOutput(true);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
// Connect to server
connection.connect();
// Create InputStreamReader to read response from server
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
// Create BufferedReader to read through InputStream
BufferedReader reader = new BufferedReader(streamReader);
// Create StringBuilder to hold our result
StringBuilder stringBuilder = new StringBuilder();
// Check if the line read is null
while ((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
// Close out InputStream and BufferedReader
reader.close();
streamReader.close();
// Set result to stringBuilder
result = stringBuilder.toString();
connection.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
return result;
}
The server uses the Spring framework, and according to my partner, did not use a JSONObject.

Java Bitstamp API market order File not Found

I am trying to make a post from Java to make a market order using my Bitstamp account but the following code is returning a file not found for the URL.
It may be because of CSRF but I am unsure, if anyone has had any experience with the bitstamp API that would be great.
public static void postToken() throws IOException, JSONException {
URL url = null;
String sig = encode();
try {
url = new URL("https://www.bitstamp.net/api/v2/buy/market/" + feedbackType.toLowerCase() +"usd/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);//5 secs
connection.setReadTimeout(5000);//5 secs
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject cred = new JSONObject();
cred.put("key",api_key);
cred.put("signature", sig);
cred.put("nonce", nonce);
cred.put("amount", feedback);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(cred.toString());
out.flush();
out.close();
int res = connection.getResponseCode();
System.out.println(res);
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine() ) != null) {
Log.d(TAG, line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Error: W/System.err: java.io.FileNotFoundException: https://www.bitstamp.net/api/v2/buy/market/btcusd/

Getting Null response From Async task With Response code 200 which means Success

When I Debug my code get Response code 200 which means success. Then also I'm getting null response.
Following is my AsyncTask Class:
private class AsyncAddfriend extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://ishook.com/users/friends/send_friend_request_json/");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
}else{
return("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}}
I have Tested My API in postman its Working with response code 200 and giving Response in json format but in my code its not working .
Hope you will understand my problem.
Thank you very much for your time and assistance in this matter.
The problem is probably from this line:
String query = builder.build().getEncodedQuery();
You need to use:
String query = builder.build().toString();
This is because getEncodedQuery() is only returning the query, from the documentation:
String getEncodedQuery ()
Gets the encoded query component from this URI. The query comes after the query separator ('?') and before the fragment separator ('#'). This method would return "q=android" for "http://www.google.com/search?q=android".
UPDATED
You're building the query after opening the connection, hence you having the error.
You need to build the url with the query first:
Uri uri = Uri.parse("http://ishook.com/users/friends/send_friend_request_json/")
.buildUpon()
.appendQueryParameter("sessionId", params[0])
.appendQueryParameter("UserId", params[1])
.appendQueryParameter("friendId", params[2]);
.build();
URL url = new URL(builtUri.toString());
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
Note: I haven't test the code. So, don't expected it working automagically.

HttpURLConnection always failing with 401

I'm trying to use HttpURLConnection for connecting to server from Android app which I'm developing. For now, I'm testing the connection code not in an app but as a plain java program with main class. I guess this doesn't make any difference as far as HttpUrlConnection.
Please examine the code snippet. Another issue is even errorStream is throwing null. This I feel is because of malformed URL.
private static String urlConnectionTry() {
URL url; HttpURLConnection connection = null;
try {
String urlParameters = "email=" + URLEncoder.encode("email", "UTF-8") +
"&pwd=" + URLEncoder.encode("password", "UTF-8");
//Create connection
url = new URL("http://example.com/login");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("uuid", getUuid());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
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();
}
}
}
private static String getUuid() {
try {
Document doc=Jsoup.connect("http://example.com/getUuid").get();
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
if(metaElem.attr("name").equals("uuid")) {
return metaElem.attr("content");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You're probably receiving 401 because the credentials that was sent to the server is not authorized- it's probably not registered or the password is incorrect.
As for the null error stream, take a look at this SO answer.
If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null.
It is probably better if you check first the response code using HttpUrlConnection#getResponseCode(). Decide on whether you'll be checking the contents of the error stream based on the response code you get.

Using Java (HttpURLConnection) to authenticate to Restheart (for Mongodb)

I am using restheart to provide a restful interface to mongodb. The interface is set up and running and provides the correct answer if a GET request is sent through Chrome. However if I use the following java code using a HttpURLConnection I get a 201 response with no content.
try {
videos = new URL("http://www.example.com:8080/myflix/videos");
} catch (Exception et) {
System.out.println("Videos URL is broken");
return null;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) videos.openConnection();
String login="admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic "+encoded);
hc.setDoInput(true);
hc.setDoOutput(true);
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Content-Type", "application/json");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
return (null);
}
BufferedReader br = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(
hc.getOutputStream());
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
String inputLine;
String sJSON = null;
try {
int rc = hc.getResponseCode();
What is the correct way to authenticate using Java to the resthert interface? (Details on the restheart authentication is here Restheart authentication
I made few changes (look for inline comments starting with <==) and it works:
The way you generate the authentication request header is correct. When I run your code I actually got 415 Unsupported Media Type, that went away commenting out hc.setDoOutput(true). A GET is a input operation, in fact you were also trying to get an OutStream from the connection: you need to get an InputStream actually.
URL url;
try {
url = new URL("http://127.0.0.1:8080/test/huge");
} catch (Exception et) {
System.out.println("Videos URL is broken");
Assert.fail(et.getMessage());
return;
}
HttpURLConnection hc = null;
try {
hc = (HttpURLConnection) url.openConnection();
String login = "admin:admin";
final byte[] authBytes = login.getBytes(StandardCharsets.UTF_8);
final String encoded = Base64.getEncoder().encodeToString(authBytes);
hc.addRequestProperty("Authorization", "Basic " + encoded);
System.out.println("Authorization: " + hc.getRequestProperty("Authorization"));
hc.setDoInput(true);
//hc.setDoOutput(true); <== removed, otherwise 415 unsupported media type
hc.setUseCaches(false);
hc.setRequestMethod("GET");
hc.setRequestProperty("Accept-Encoding", "gzip, deflate, sdch");
hc.setRequestProperty("Accept", "application/json,text/html,application/hal+json,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*");
} catch (Exception et) {
System.out.println("Can't prepare http URL con");
}
System.out.println(hc.toString());
BufferedReader br = null;
try {
InputStreamReader reader = new InputStreamReader(hc.getInputStream()); // <== the request is a GET, data is in input
} catch (Exception et) {
System.out.println("Can't get reader to videos stream");
}
int rc = hc.getResponseCode();
System.out.println("response code: " + rc);
System.out.println("response message: " + hc.getResponseMessage());
Assert.assertEquals(200, rc);

Categories

Resources