I have a Dynamic Web Project + Maven deployed on WebSphere 8.5 with java 1.6 and I'm using the following library in the pom.xml:
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
I get the environment's url and I'm trying to write it on a .json file.
Here is the code:
InetAddress ip;
try {
ip = InetAddress.getLocalHost();
ip.getHostAddress();
JSONObject obj = new JSONObject();
obj.put("name", "https:" + File.separatorChar + File.separatorChar + ip.getHostAddress() + ":443"
+ File.separatorChar + "authorizer" + File.separatorChar);
obj.put("debugging", "true");
FileWriter file = new FileWriter(ctx.getServletContext().getRealPath("/") + "/assets/conf.json");
file.write(obj.toJSONString());
file.flush();
file.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Well it works, but I get this on conf.json:
{"name":"https:\/\/126.0.0.0:443\/authorizer\/","debugging":"true"}
As you see, it is not formatted but when I have tested it on Windows just worked fine.
The thing is when I deployed on WebSphere I got the url wrong and the problem It's on the way of the forward slash. How can I write the url correctly?
I have tried already with File.separator, or simply writing "/" or "\\" but neither worked.
Don't use File.separator to construct URLs, simply use /. The path-separator for URLs is the same regardless of the OS. File.separator is different depending on the OS (Windows is \, most other OSs are /). I rewrote a portion of your code to demo the construction of the URL. Notice when you get the URL from the Json object, it is formatted properly (see the line: System.out.println("the URL recovered from Json:...). The output from that line looks like:
the URL recovered from Json: https://127.0.1.1:443/authorizer/
public static void main(String... args) throws Exception {
InetAddress ip;
ip = InetAddress.getLocalHost();
ip.getHostAddress();
String url0 = "https:" + File.separatorChar + File.separatorChar + ip.getHostAddress() + ":443"
+ File.separatorChar + "authorizer" + File.separatorChar;
String url1 = "https:" + "//" + ip.getHostAddress() + ":443"
+ "/" + "authorizer" + "/";
JSONObject obj = new JSONObject();
obj.put("name", url0);
obj.put("debugging", "true");
System.out.println("the URL recovered from Json: " + obj.get("name"));
System.out.println("json: " + obj.toJSONString());
System.out.println("this url will be different than what you want on Windows:\n" + url0);
System.out.println("this is what you want, it will be the same on all OSs:\n" + url1);
}
It appears that Json allows / to be escaped, but does not require it. So escaping the / is not incorrect, just unnecessary in your case. See: JSON: why are forward slashes escaped?
Related
I want to get a list with all files and dirs in a dir located on a sharepoint
I do not have experience with REST api and I can not find this specific problem solved on google
I have the current code:
HttpURLConnection sharepoint = new LoginManager().login();
String siteURL = "https://confidential.sharepoint.com/something/"; //here <siteURL_path> is '/teams/SPdev/AlertsCount'
String wsUrl = siteURL + "/_api/web/GetFolderByServerRelativeUrl('TheFolder')";
//Send Request
InputStream in = sharepoint.getInputStream();
//Read the response.
String responseStr = "";
if (sharepoint.getResponseCode() == 302)
{
responseStr = "Folder read. ResponseCode: " + sharepoint.getResponseCode();
}
else
{
responseStr += "Error while reading folder, ResponseCode: " + sharepoint.getResponseCode() + " " + sharepoint.getResponseMessage();
}
System.out.println(responseStr);
Where LoginManager is something I did folowing this:
https://social.technet.microsoft.com/Forums/office/en-US/4c8d3696-1d41-44e3-897c-ac3c0b44f66a/share-point-online-authentication-using-java?forum=sharepointsearch
I'm trying to use the org.apache.commons.vfs2 to download a file via SFTP.
The problem is, the password contains the '#' char, so this causes the URI to be parsed incorrectly:
org.apache.commons.vfs2.FileSystemException: Expecting / to follow the hostname in URI
Does anyone has an idea how to get around this issue? (I can't change the password, obviously). This is the code I'm using:
String sftpUri = "sftp://" + userName + ":" + password + "#"
+ remoteServerAddress + "/" + remoteDirectory + fileName;
String filepath = localDirectory + fileName;
File file = new File(filepath);
FileObject localFile = manager.resolveFile(file.getAbsolutePath());
FileObject remoteFile = manager.resolveFile(sftpUri, opts);
localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
Use an actual URI constructor instead of hand-rolling your own:
String userInfo = userName + ":" + password;
String path = remoteDirectory + filename; // Need a '/' between them?
URI sftpUri = new URI("sftp", userInfo, remoteServerAddress, -1, path, null, null);
...
FileObject remoteFile = manager.resolveFile(sftpUri.toString(), opts);
You need to encode the your password by UriParser.encode(), you can change your code like below:
you code:
String sftpUri = "sftp://" + userName + ":" + password + "#"
+ remoteServerAddress + "/" + remoteDirectory + fileName;
change to:
String sftpUri = "sftp://" + userName + ":" + **UriParser.encode(password, "#".toCharArray())**+ "#"
+ remoteServerAddress + "/" + remoteDirectory + fileName;
Hope it help, thank you.
I have a question about URI and URL
when i pass a url is work good but result is worst need help!!
as my code look like this.
import java.io.*;
import java.net.*;
import java.net.URL;
public class isms {
public static void main(String[] args) throws Exception {
try {
String user = new String ("boo");
String pass = new String ("boo");
String dstno = new String("60164038811"); //You are going compose a message to this destination number.
String msg = new String("你的哈达哈达!"); //Your message over here
int type = 2; //for unicode change to 2, normal will the 1.
String sendid = new String("isms"); //Malaysia does not support sender id yet.
// Send data
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass
+ "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
URL url = new URL(myUrl.toASCIIString());
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Print the response output...
System.out.println(line);
}
rd.close();
System.out.println(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
the output in web is different..
on my java output is
你的哈达哈达!
but on my the site is
ÄãµÄ¹þ´ï¹þ´ï!
Help!!
String user = new String ("boo");
You don't need to (and shouldn't) do new String in Java—String user = "boo"; is fine.
String msg = new String("你的哈达哈达!");
Writing non-ASCII characters in your source means that you have to get the -encoding flag to javac to match the encoding you have saved your text files with. It is possible you have saved the .java file as UTF-8 but not configured your build environment to use UTF-8 at compile time.
If you are not sure that you've got this right, you can use ASCII-safe \u escapes in the meantime:
String msg = "\u4F60\u7684\u54C8\u8FBE\u54C8\u8FBE!"; // 你的哈达哈达!
Finally:
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?un=" + user + "&pwd=" + pass
+ "&dstno=" + dstno + "&msg=" + msg + "&type=" + type + "&sendid=" + sendid);
When you're putting a URI together you should URL-escape each of the parameters you include in the string. Otherwise any & or other invalid character in the value will break the query. This also allows you to choose what charset is used to create the query string.
String enc = "UTF-8";
URI myUrl = new URI("http://www.isms.com.my/isms_send.php?" +
"un=" + URLEncoder.encode(user, enc) +
"&pwd=" + URLEncoder.encode(pass, enc) +
"&dstno=" + URLEncoder.encode(dstno, enc) +
"&msg=" + URLEncoder.encode(msg, enc) +
"&type=" + URLEncoder.encode(Integer.toString(type), enc) +
"&sendid=" + URLEncoder.encode(sendid, enc)
);
What the right value for enc is depends on the service you are connecting to, but UTF-8 is a good guess.
i had some difficulties in programming and the meaning of the Request Body is confused. It always returns 400 response codes.Please help me.
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments+=URLEncoder.encode("client", "UTF-8")+"="+URLEncoder.encode("demo-app", "UTF-8")+"&";
arguments+=URLEncoder.encode("apikey", "UTF-8")+"="+URLEncoder.encode("apikey", "UTF-8")+"&";
arguments+=URLEncoder.encode("appver", "UTF-8")+"="+URLEncoder.encode("1.5.2", "UTF-8")+"&";
arguments+=URLEncoder.encode("pver", "UTF-8")+"="+URLEncoder.encode("3.0", "UTF-8")+"&";
arguments+=URLEncoder.encode("post_req_body", "UTF-8")+"="+URLEncoder.encode("2\nhttp://www.google.com\nhttp://www.facebook.com", "UTF-8");
String query = arguments;
System.out.println("Sending POST request - " + query);
// Construct the url object representing cgi script
URL url = new URL( baseURL );
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print ( query );
pout.close();
Your request is wrong. If you use a POST request, then the parameters client, apikey, apiver and pver should be part of the URL.
The request body should only consist of the URLs to check (plus the number of URLS on the first line).
So it could look like this:
String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments + =URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
arguments + =URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12341234", "UTF-8") + "&";
arguments + =URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
arguments + =URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");
// Construct the url object representing cgi script
URL url = new URL(baseURL + "?" + arguments);
// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();
// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);
// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print("2");
pout.println();
pout.print("http://www.google.com");
pout.println();
pout.print("http://www.facebook.com");
pout.close();
New to java, GWT and interacting with APIs. I have what I hope is a simple question.
I have successfully interacted with a REST API using the following curl command:
curl -d "OPERATION_NAME=ADD_REQUEST&TECHNICIAN_KEY=xxxxxxxxxxx&INPUT_DATA=<?xml version=%221.0%22 encoding=%22utf-8%22?><Operation><Details><requester>Me</requester><subject>Test</subject><description>Testing curl input</description></Details></Operation>" http://xx.xx.xx.xx/sdpapi/request/
Now, from a tutorial, I have the following code that I am hoping will post a request to the remote server just like the curl command above.
What I am trying to figure out (with no love from google) is how I pass the OPERATION_NAME, TECHNICIAN_KEY and INPUT_DATA parameters in when I am sending the URL. Any suggestions, tutorials, etc. will be appreciated.
The following is from my server side implementation interface:
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
//dividing url into host: http://some.server
//path: a/path/in/it
//and parameters: this=that&those=others
int hostStart= serviceUrl.indexOf("//");
int pathStart= serviceUrl.substring(hostStart + 2).indexOf("/");
int parameterStart= serviceUrl.substring(hostStart + 2 + pathStart).indexOf("?");
final String serverHost= serviceUrl.substring(0, hostStart + pathStart + 2);
final String serverPath= serviceUrl.substring(hostStart + 3,
hostStart + pathStart + 2 + parameterStart);
final String serverParameters= serviceUrl.substring(hostStart + pathStart + 3 + parameterStart);
final URL url = new URL(serverHost);
final URLConnection connection= url.openConnection();
connection.setDoOutput(true);
final OutputStreamWriter out= new OutputStreamWriter(connection.getOutputStream());
final BufferedReader in= new BufferedReader(new InputStreamReader(
connection.getInputStream()));
out.write("POST " + serverPath + "\r\n");
out.write("Host: " + serverHost + "\r\n");
out.write("Accept-Encoding: identity\r\n");
out.write("Connection: close\r\n");
out.write("Content-Type: application/x-www-form-urlencoded\r\n");
out.write("Content-Length: " + serverParameters.length() + "\r\n\r\n" +
serverParameters + "\r\n");
String result = "";
String inputLine;
while ((inputLine=in.readLine()) != null) {
result+= inputLine;
}
in.close();
out.close();
return result;
} catch (final Exception e) {
throw new HelpDeskTestException();
}
Consider using this library: Apache HttpClient. Here is an example of making a POST request with it.