OrientDB http request failed...? - java

I'm trying to do a "POST" method in Java. I create my output with the OrientDB method like this:
"http://xxxxxxxxxxx:2480/command/mydb/sql/CREATE VERTEX V SET name = ' datoAletarorio'"
I need to use the write and flush methods to send the command.
My DB is empty with this method.
Where is my error? Here is my code:
//...
PrintWriter out = null;
//...
conexion = (HttpURLConnection) url.openConnection();
conexion.setDoOutput(true);
conexion.setRequestMethod("POST");
out = new PrintWriter(conexion.getOutputStream());
conexion.connect();
//...
String cumuloDatos1 = "http://xxxxxxxxxxx:2480/command/mydb/sql/CREATE VERTEX V SET name = ' datoAletarorio'"
out.write(cumuloDatos1);
out.flush();
//..
conexion.disconnect();
Thank in advance.

The docs says:
The command-text can appear in either the URL or the content of the
POST transmission. Where the command-text is included in the URL, it
must be encoded as per normal URL encoding.
So you probably have to encode the URL before sending the request:
String cumuloDatos1 =
"http://xxxxxxxxxxx:2480/command/mydb/sql/" +
"CREATE%20VERTEX%20V%20SET%20name%20%3D%20%27%20datoAletarorio%27"
Anyway, you should see messages in the logs for a 400 or similiar in the server, if the request isn't valid.

Related

Java POST request doesn't send variables

I have a problem. I have the following PHP page:
<?php
header('Content-Type: application/json');
echo $_POST["agentid"];
?>
And my Java code is the following:
public String callWebpage(String strUrl, HashMap<String, String> data) throws InterruptedException, IOException {
var objectMapper = new ObjectMapper();
String requestBody = objectMapper
.writeValueAsString(data);
URL url = new URL(strUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(requestBody.getBytes("UTF-8"));
String result = convertInputStreamToString(con.getInputStream());
return result;
}
To call the function, I use the following lines:
var values = new HashMap<String, String>() {{
put("agentid", String.valueOf(agentId));
}};
String jsonResponse = webAPI.callWebpage("https://www.test.org/test.php", values);
This does print the result of the page, but it gives me:
2021-02-28 00:40:16.735 Custom error: [8] Undefined index: agentid<br>2021-02-28 00:40:16.735 Error on line 5
The page is HTTPS and I do get a response, but why is my agentid variable not getting received by the page and how can I fix this?
Please, consider including the following code in your Java connection setup to indicate that you are POSTing JSON content before writing to the connection output stream:
con.setRequestProperty("Content-Type", "application/json");
In any way, I think the problem is in your PHP code: you are trying to process raw HTTP parameter information while you are receiving a JSON fragment as the request body instead.
In order to access the raw JSON information received in the HTTP request you need something like the following:
// Takes raw data from the request.
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
// Process information
echo $data->agentid;
Please, see this link and 'php://input` for more information.
Be aware that with the above-mentioned code you are returning a String to the Java client, although you indicated header('Content-Type: application/json'), maybe it could be the cause of any problem.
I think that you are using HTTP Request. Then, use exec‌‌‌​​‌​‌‌​‌‌‌‌‌‌​​​‌​‌‌​‌‌‌‌ instead of POST if that coder is persist the same as in the answer below.

i have a controller redirect to a url I want that parameters should not be displayed as a query string

i am using
sendRedirect("http://api.mVaayoo.com/mvaayooapi/MessageCompose?user=someuser#gmail.com:123456&senderID=TEST SMS&receipientno=0987654321&dcs=0&msgtxt="+ message + "&state=4")
to call mvaayoo api for sendind sms .But the parameters are displayed in address bar to the client .
Is there a way to hide query string? I dont want to purchase SSL certificate.
The problem is not how you redirect, rather the problem is in the provider of the redirect URL you are trying to use:
http://api.mVaayoo.com/mvaayooapi/MessageCompose
No sensitive information should be used as a GET/query param.
Is there a way to hide query string?
Pass additional data as redirect attributes instead of passing it as query parameters.
To carry data across a redirect use RedirectAttributes#addFlashAttribute(key, value).
What Java doc says:
A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.
After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.
Read more...
Take a look
List<String> pathParam = null;
if(null!=request.getPathInfo() && !request.getPathInfo().trim().isEmpty()){
String paths[] = this.getPathInfo().replaceAll("\\/$|^\\/", "").split("/");
pathParam = new ArrayList<>(Arrays.asList(paths));
}
// assume your servlet url is "/login/*"
// called url in browser /login/param1/param2/param3
String param1 = pathParam.get(0);
String param2 = pathParam.get(1);
String param3= pathParam.get(2);
You need to use URLConnection to achieve this:
HTTP GET:
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
Target URL's doGet() method will be called and the parameters will be available by HttpServletRequest#getParameter().
HTTP POST:
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
Target URL's doGet() method will be called and the parameters will be available by HttpServletRequest#getParameter().

What is the proper way to escape a URL for URLConnection.getInputStream()?

I'm having a really bizarre problem with URLConnection.getInputStream() when I have a space (' ') in the query string portion of a URI. Specifically, I have one URL that works and another that does not, when I think they should both fail or both succeed, additionally, its every time.
Working URL: http://minneapolis.craigslist.ca/search/sss?catAbb=sss&query=iPhone+sprint&sort=date&srchType=A&format=rss
Failed URL (exception below) : http://winnipeg.craigslist.ca/search/sss?catAbb=sss&query=iPhone+sprint&sort=date&srchType=A&format=rss
conn.getInputStream() throws the IO exception: "Illegal character in query at index 67: http://winnipeg.en.craigslist.ca/search/sss?catAbb=sss&query=iPhone sprint two&sort=date&srchType=A&format=rss"
It appears openConnection can't get the space (which I've already replaced with a '+' as I'd expect to have to with a 'URL', I've also tried '%20' with the same results.
Additionally, URL.toString() reports the URLS as I printed above, with the '+' not the space.
Code is as follows, searchUrl is a 'URL' instance.
URLConnection conn = null;
conn = searchUrl.openConnection();
conn.setConnectTimeout(CONNECT_TIMEOUT);
conn.setUseCaches(true);
conn.setAllowUserInteraction(false);
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
InputStream istream = conn.getInputStream();
int numBytesRead, numBytesWritten = 0;
byte[] buffer = new byte[8 * 1024];
while ((numBytesRead = istream.read(buffer, 0, 8 * 1024)) > 0) {
oStream.write(buffer, numBytesWritten, numBytesRead);
numBytesWritten += numBytesRead;
}
Any ideas on where to deal with this? I'm about to pitch URLConnection and go another route...
Thanks
Kenny.
There is something wrong with your question (see my comment).
However, the fundamental problem here is that a URL with a space character in the query part is not a legal URL ... not withstanding that a typical web browser will accept it. The exception is therefore correct.
Your example URLs seem to show that the space is escaped with a '+'. This is HTML form escaping not proper URL escaping. You seem to be saying that you get the same result is you use %20 ... which would be correct escaping.
So my theory is that you are actually passing this URL to your code via a route that is removing the escapes ... not-withstanding what your traceprints seem to be telling you. (If I could see an SSCE we'd be able to test this theory ...)
FWIW, fixing the problem by calling UrlEncoder.encode as some of the other answers have suggested is a bad idea. The problem is that it is likely to "encode" other characters that shouldn't be encoded.
The URL itself is best encoded with new URI(null, url, null).toASCIIString().
Each key and value in the query string can be separately encoded with URLEncoder.encode(). According to RFC 2936 this isn't correct and the whole thing should be encoded as for the URL itself, but I've never seen it fail.
Did you try URLEncoder.encode(string, "UTF-8")
Following is the example:
Replace
String url = "http://somesite.com/page?user=" + user;
with
String url = "http://somesite.com/page?user="
+ URLEncoder.encode(user, "UTF-8");
String url= URLEncoder.encode("your URL without http or your query string part here");
URL searchUrl = new URL("http://" + url);
URLConnection conn = null;
conn = searchUrl.openConnection();

Problem in getting url.getContent()

I have a problem in my hand.
I have a URL, And when i initiate the connect to this url and execute url.getContent().
The response is of type sun.net.www.protocol.http.HttpURLConnection$HttpInputStream
I tried to assign the output to HttpURLConnectionHttpInputStream h = url.getContent(). But i was unsuccessful.
I imported corresponding libraries to code, but still no luck.
If i inspect the url.getContent() in eclipse, it also shows the variable thei$0 in it.
All i need is a URL in this$0. But till now i am unable to retreive it.
In this$0 there is a variable names url and i am trying to fetch it.
I also have hard time understand this$0 and hoe to retrieve it.
After using the streams i get some non readable output
Regards
Dheeraj Joshi
You should use the openStream method of the url class.
Code snippet:
InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
If the output is not in a readable string format, then use:
InputStream in = url.openStream();
byte[] buffer = new byte[512];
int bytesRead = in.read(buffer);
I found the answer.
The problem statement: When i execute a URL the response had another URL in it and i needed to fetch it.
Solution:
java.net.URLConnection urlconn = url.openConnection();
java.net.HttpURLConnection conn = (java.net.HttpURLConnection)urlconn;
conn.connect();
conn.getContent();
URL newurl = conn.getURL();
System.out.println(newurl.toString());
The response can be get using getContent() and. The connection object will have a delegate with the new URL. The new URL can be fetched using getURL method.
Regards
Dheeraj Joshi

FileNotFoundException while getting the InputStream object from HttpURLConnection

I am trying to send a post request to a url using HttpURLConnection (for using cUrl in java).
The content of the request is xml and at the end point, the application processes the xml and stores a record to the database and then sends back a response in form of xml string. The app is hosted on apache-tomcat locally.
When I execute this code from the terminal, a row gets added to the db as expected. But an exception is thrown as follows while getting the InputStream from the connection
java.io.FileNotFoundException: http://localhost:8080/myapp/service/generate
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)
at org.kodeplay.helloworld.HttpCurl.main(HttpCurl.java:30)
Here is the code
public class HttpCurl {
public static void main(String [] args) {
HttpURLConnection con;
try {
con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
File xmlFile = new File("test.xml");
String xml = ReadWriteTextFile.getContents(xmlFile);
con.getOutputStream().write(xml.getBytes("UTF-8"));
InputStream response = con.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(response));
for (String line ; (line = reader.readLine()) != null;) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Its confusing because the exception is traced to the line InputStream response = con.getInputStream(); and there doesn't seem to be any file involved for a FileNotFoundException.
When I try to open a connection to an xml file directly, it doesn't throw this exception.
The service app uses spring framework and Jaxb2Marshaller to create the response xml.
The class ReadWriteTextFile is taken from here
Thanks.
Edit:
Well it saves the data in the DB and sends back a 404 response status code at the same time.
I also tried doing a curl using php and print out the CURLINFO_HTTP_CODE which turns out to be 200.
Any ideas on how do I go about debugging this ? Both service and client are on the local server.
Resolved:
I could solve the problem after referring to an answer on SO itself.
It seems HttpURLConnection always returns 404 response when connecting to a url with a non standard port.
Adding these lines solved it
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.
Replace
InputStream response = con.getInputStream();
by
int status = con.getResponseCode();
All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.
If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.
InputStream error = con.getErrorStream();
FileNotFound is just an unfortunate exception used to indicate that the web server returned a 404.
To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.
In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.
If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.
For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream(); came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream(); which is the incorrect order of things.
ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "http response code is " + conn.getResponseCode());
return null;
}
InputStream in = conn.getInputStream();
FileNotFound in this case was an unfortunate way to encode HTTP response code 400.
FileNotFound in this case means you got a 404 from your server - could it be that the server does not like "POST" requests?
FileNotFound in this case means you got a 404 from your server
You Have to Set the Request Content-Type Header Parameter
Set “content-type” request header to “application/json” to send the request content in JSON form.
This parameter has to be set to send the request body in JSON format.
Failing to do so, the server returns HTTP status code “400-bad request”.
con.setRequestProperty("Content-Type", "application/json; utf-8");
Full Script ->
public class SendDeviceDetails extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String data = "";
String url = "";
HttpURLConnection con = null;
try {
// From the above URL object,
// we can invoke the openConnection method to get the HttpURLConnection object.
// We can't instantiate HttpURLConnection directly, as it's an abstract class:
con = (HttpURLConnection)new URL(url).openConnection();
//To send a POST request, we'll have to set the request method property to POST:
con.setRequestMethod("POST");
// Set the Request Content-Type Header Parameter
// Set “content-type” request header to “application/json” to send the request content in JSON form.
// This parameter has to be set to send the request body in JSON format.
//Failing to do so, the server returns HTTP status code “400-bad request”.
con.setRequestProperty("Content-Type", "application/json; utf-8");
//Set Response Format Type
//Set the “Accept” request header to “application/json” to read the response in the desired format:
con.setRequestProperty("Accept", "application/json");
//To send request content, let's enable the URLConnection object's doOutput property to true.
//Otherwise, we'll not be able to write content to the connection output stream:
con.setDoOutput(true);
//JSON String need to be constructed for the specific resource.
//We may construct complex JSON using any third-party JSON libraries such as jackson or org.json
String jsonInputString = params[0];
try(OutputStream os = con.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
}
int code = con.getResponseCode();
System.out.println(code);
//Get the input stream to read the response content.
// Remember to use try-with-resources to close the response stream automatically.
try(BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))){
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result); // this is expecting a response code to be sent from your server upon receiving the POST data
}
and call it
new SendDeviceDetails().execute("");
you can find more details in this tutorial
https://www.baeldung.com/httpurlconnection-post
The solution:
just change localhost for the IP of your PC
if you want to know this: Windows+r > cmd > ipconfig
example: http://192.168.0.107/directory/service/program.php?action=sendSomething
just replace 192.168.0.107 for your own IP (don't try 127.0.0.1 because it's same as localhost)
Please change
con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();
To
con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

Categories

Resources