I want to send datas from my Java program to a Tine2.0 server. I have found a solution called JSON-RPC for Java, working on the Post http method.
I have already created a class doing a Post request to a test page of the server, this is the code:
import java.io.*;
import java.net.*;
public class EnvoiEnBaseViaURL {
public static void main(String[] args) throws Exception {
String tacheSent = URLEncoder.encode(args[0], "UTF-8"); //args[0] = "tache a envoyer"
String noteSent = URLEncoder.encode(args[1], "UTF-8"); //args[1] = "note a envoyer"
String dossier = URLEncoder.encode(args[2], "UTF-8"); //args[2] = "dossier a envoyer"
String context = URLEncoder.encode(args[3], "UTF-8"); //args[3] = "contexte a envoyer"
String iD = URLEncoder.encode(args[4], "UTF-8");
String pass = URLEncoder.encode(args[5], "UTF-8");
URL url = new URL(args[6]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("TacheEnvoyee=" + tacheSent + "&NoteEnvoyee=" + noteSent + "&Dossier=" + dossier + "&Contexte=" + context + "&Identifiant=" + iD + "&Password=" + pass);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}
It works, I successfully send datas to this page and it returns me what I have sent. But now I work with the Tine2.0 server, I have to use authentication to connect.
I have tried to follow this tutorial: https://github.com/briandilley/jsonrpc4j, I have dowloaded the ZIP file but I dont know what am I supposed to do with, Where I have to send it...(the tutorial don't explain it at all...) At the moment, the Useron the public Interface UserServicedoesn't exist, etc...
I think I can do what I want to just with
JsonRpcHttpClient client = new JsonRpcHttpClient(
new URL("http://example.com/UserService.json"));
User user = client.invoke("createUser", new Object[] { "bob", "the builder" }, User.class);
But Java, obviously, as said previously, don't recognize JsonRpcHttpClient or User..
If anyone already worked with JSON-RPC and and can explain me what am I supposed to do, maybe install or add to the Java Build Path?
I hope i'm enough concise, don't hesitate to ask informations is some are missing.
Thank you.
Related
i must send one text string using java to a IP web cam, before it take picture. So after I read the camera user manual and searched in google, the only thing i found was using cURL. I install it and its run fine, and everything is okay, the text from the file appear in the video streaming. The command is this
curl -T test.xml http://admin:pass#192.168.0.1/Video/inputs/channels/2/overlays/text/2
and the content of test.xml is:
<TextOverlay xmlns="http://www.hikvision.com/ver10/XMLSchema" version="1.0">
<id>2</id>
<enabled>true</enabled>
<posX>5</posX>
<posY>5</posY>
<message>Text here </message>
</TextOverlay>
So I want to send this content using Java, I already tried using post and java.net but I get an error "Server returned HTTP response code: 403 for URL"
Here is my code:
System.out.println("Starting......");
URL url = new URL("http://192.168.0.1/Video/inputs/channels/2/overlays/text/2/");
String data = "<TextOverlay xmlns=\"http://www.hikvision.com/ver10/XMLSchema\" version=\"1.0\">\n"
+ "<id>2</id>\n"
+ "<enabled>true</enabled>\n"
+ "<posX>5</posX>\n"
+ "<posY>5</posY>\n"
+ "<message>Text here</message>\n"
+ "</TextOverlay>";
HttpURLConnection httpConnection = prepareConn(url, null, "admin", "pass");
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty ( "Content-Type", "text/xml" );
OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
out.write(data);
out.flush();
out.close();
System.out.println("Printing......");
System.out.println(httpConnection.getResponseCode());
System.out.println(httpConnection.getResponseMessage());
InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[2048];
int num;
while(-1 != (num = reader.read(cbuf)))
{
buf.append(cbuf, 0, num);
}
String result = buf.toString();
System.out.println("\nResponse received from server after POST" + result);
}
static private HttpURLConnection prepareConn(final URL url, Properties request_props, String username, String password) throws Error, IOException
{
System.out.println("Authorization......");
if (!url.getProtocol().equalsIgnoreCase("http"))
throw new Error(url.toString() + " is not HTTP!");
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(300);
conn.setRequestMethod("POST");
final Properties DEFAULT_REQUEST_PROPS = new Properties();
DEFAULT_REQUEST_PROPS.setProperty("charset", "utf-8");
final Properties props = new Properties(DEFAULT_REQUEST_PROPS);
if (request_props != null)
for (final String name : request_props.stringPropertyNames())
props.setProperty(name, request_props.getProperty(name));
for (final String name : props.stringPropertyNames())
conn.setRequestProperty(name, props.getProperty(name));
if(null != username && null != password)
conn.setRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode((username+":"+password).getBytes()));
return conn;
}
Hope someone can help :)
All the best !
I just use wrong RequestMethod, after deep research I found that i must use PUT not POST request. Now just change setRequestMethod("POST") to setRequestMethod("PUT") and works like a charm.
hi guys i want to code a tool, which interacts with phpmyadmin. I want to create a new Table. For this i need the cookie and the security token. Both things I've done. My Problem is i'll take the cookies and open an new URLConnection with these Cookies. And take the token to validate my request. But everytime i do this i got the response that my SQLQuery is empty and if u get this Error ur token is invalid. And an invalid token means that ur cookies haven't been placed very well in the new connection so u don't have the same session as before. What i've done wrong, any idea to fix this problem?
Here is my code:(its very ugly but its only for testing purposes)
import java.io.*;
import java.net.*;
import java.util.List;
public class connect {
public void connectto() throws IOException{
URLConnection connection = new URL("http://localhost/phpmyadmin/index.php").openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
connection.connect();
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
String line;
String token = "";
while((line = br.readLine())!= null){
System.out.println(line);
if (line.contains("var token = ")){
System.out.println("hit");
token = "&token=" + line.substring(line.indexOf("var token = '") + "var token = '".length()).substring(0, line.substring(line.indexOf("var token = '") + "var token = '".length()).indexOf("';"));
}
}
System.out.println(token);
String url = URLEncoder.encode("db=mysql&sql_query=CREATE TABLE testtable(testtable TEXT);" + token, "UTF-8");
connection = new URL("http://localhost/phpmyadmin/sql.php?" + url).openConnection();
connection.setDoOutput(true);
for (String cookie : cookies) {
System.out.println(cookie.split(";", 2)[0]);
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
connection.connect();
response = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(response));
line = "";
while((line = br.readLine())!= null){
System.out.println(line);
}
}
}
My apologies if I misunderstood your issue but why are you forcing the request through phpMyAdmin? The point of phpMyAdmin is to provide a UI to people to work with their MySQL database. If you want to interact with the MySQL database you should be opening a connection directly to the database and executing statements in the java code.
Again, please excuse my ignorance if this is unfeasable for you but if you must work through phpMyAdmin instead of a direct connection between Java and your DB please provide more information.
I'm trying to setup a basic call to a Spring service using the URL package so that I can do it through a POST rather than get.
Client code (the code calling the spring service):
String data = URLEncoder.encode("testStringFromGWT", "UTF-8") + "=" + URLEncoder.encode(message, "UTF-8");
URL url = new URL("http://localhost:8080/spring-hibernate-mysql/test/test1");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
The Spring service:
#RequestMapping(value = "/test1", method = RequestMethod.POST)
public String loggedInUniversal_logout(
Model model,
HttpServletRequest request,
#RequestParam(value = "inputString", required = true) String inputString)
throws InterruptedException {
HttpSession session = request.getSession();
System.out.println("Request made from Client..." + inputString);
model.addAttribute("token", "It works");
return "token";
}
When I try this I get:
java.io.FileNotFoundException: http://localhost:8080/spring-hibernate-mysql/test/test1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)
I'm not quite sure what I am doing wrong, I am able to confirm that the call is being passed through properly to Spring as I can see the line being printed "Request made from Client..." + inputString but then I get the FileNotFoundException on the client. I pieced this together from looking at tutorials so I guess I am missing something here, would appreciate any advice.
Close the output stream before trying to read from the input stream in your example above.
As an alternative, use a http client library like HTTPClient or Resty.
With Resty, your client code would look like this:
Resty r = new Resty();
String result = r.text(url).toString();
for a GET
and for a POST using a simple form:
r.text(url,form(yourformdata)).toString();
Disclaimer: I'm the author of Resty
I'm testing aut-renewable subscription but apple's sandbox server always returns status=21004, which means 'The shared secret you provided does not match the shared secret on file for your account.'.
I test with a java server, which does mostly this:
String receiptData = "theReceiptDataBytesBase64encoded";
String sharedSecret = "theSharedSecretAsPureStringProvidedByItunesconnect";
String jsonData = "{" +
"\"receipt-data\" : \"" + receiptData + "\"," +
"\"passsword\" : \"" + sharedSecret + "\"" +
"}";
URL url = new URL("https://sandbox.itunes.apple.com/verifyReceipt");
HttpURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(jsonData);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = rd.readLine()) != null)
{
System.out.println(line);
}
wr.close();
rd.close();
As I tried to clear up by variable values in code sample above, I didn't encode the shared secret, using it as a plain string. Is this the problem?
Those are days that make you feel so great to be a developer ...
Looking carefully at my question above you'll see that I used the JSON key passsword with 3 friggin' s characters !!! That was the reason for a 5 hour try-and-error experience with several test products and test users and new shared secrets in the app store sandbox.
Special thanks to the iTunes team for giving the 'wrong shared secret'-message instead of the 'what the heck is the passsword key'-message.
I have a program in Java where I retrieve contents from a database.
Now I have a form in the program, and what I want to do is, on the press of a button, some string (text) content retrieved from the database, should be sent over to a website that I'm hosting locally. The content so sent, should be displayed on the website when refreshed.
Can someone guide me as to how I can achieve this (the sending of data to be displayed over the website)?
Will appreciate a lot, if you could kindly show some sample snippets or give me a reference to some tutorial that can help.
---- Okay so i found a link to a snippet that's supposed to do this, but im unable to understand at this stage as to how exactly this snippet works...can someone please guide me into knowing this better ?
here's the code
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Send data
URL url = new URL("http://hostname:80/cgi");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
I'm not sure on how you store and manage any of the records but from Java you can send a HTTP Post to the Url (In your case http://localhost/, probably).
Have a look at http://www.exampledepot.com/egs/java.net/post.html for a snippet on how to do this.
Your Website could then store the received information in a database and display it when you refresh.
Update heres the function
Just a side not this is by no means the best way to do this and I have no idea on how this scales but for simple solutions this has worked for me in the past.
/**
* Posts a Set of forms variables to the Remote HTTP Host
* #param url The URL to post to and read
* #param params The Parameters to post to the remote host
* #return The Content of the remote page and return null if no data was returned
*/
public String post(String url, Map<String, String> params) {
//Check if Valid URL
if(!url.toLowerCase().contains("http://")) return null;
StringBuilder bldr = new StringBuilder();
try {
//Build the post data
StringBuilder post_data = new StringBuilder();
//Build the posting variables from the map given
for (Iterator iter = params.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String value = (String)entry.getValue();
if(key.length() > 0 && value.length() > 0) {
if(post_data.length() > 0) post_data.append("&");
post_data.append(URLEncoder.encode(key, "UTF-8"));
post_data.append("=");
post_data.append(URLEncoder.encode(value, "UTF-8"));
}
}
// Send data
URL remote_url = new URL(url);
URLConnection conn = remote_url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(post_data.toString());
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = rd.readLine()) != null) {
bldr.append(inputLine);
}
wr.close();
rd.close();
} catch (Exception e) {
//Handle Error
}
return bldr.length() > 0 ? bldr.toString() : null;
}
You would then use the function as follows:
Map<String, String> params = new HashMap<String, String>();
params.put("var_a", "test");
params.put("var_b", "test");
params.put("var_c", "test");
String reponse = post("http://localhost/", params);
if(reponse == null) { /* error */ }
else {
System.out.println(reponse);
}
The big question is how will you authenticate the "update" from your Java program to your website?
You could easily write a handler on your website, say "/update" which saves the POST body (or value of a request parameter) to a file or other persistent store but how will you be sure that only you can set that value, instead of anybody who discovers it?