Unable to write to Text File Exist in FTP server - java

I use below code to write to text file that exists in FTP server.but got java.net.MalformedURLException
URL url = new URL("ftp://p#g.com:g#1234#ftp.xyz.com/testjar/2014-03-06-p.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
ObjectOutput output = new ObjectOutputStream(buffer);
output.writeObject("hiiiii");
buffer.close();
os.close();
output.close();
above username and password is not real but its demo that looks like real.
anybody know how to solve this issue or other method to write into a .txt file,let me inform.
Edit1:also my username and pass contains # char and in pass number is there.
Full Error:
java.net.MalformedURLException: For input string: "g#1234#ftp.xyz.com"
at java.net.URL.<init>(URL.java:619)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at CreateFolder.uploadfile(CreateFolder.java:39)
at CreateFolder.main(CreateFolder.java:74)
Caused by: java.lang.NumberFormatException: For input string: "g#1234#ftp.xyz.com"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at java.net.URLStreamHandler.parseURL(URLStreamHandler.java:217)
at java.net.URL.<init>(URL.java:614)
... 4 more

You didn't provide us with the error you get but I see couple of issues here:
Connection string: I know it's an example but if real user/pass contain '#' char, the URL won't be parsed.
ObjectOutputStream class is intended to write object data so it can be reconstructed by ObjectInputStream (see here). It's not for writing textual files. If all you need is writing String to stream better use PrintStream
So the revised example will be:
try {
URL url = new URL("ftp://user:pass#ftp.xyz.com/testjar/2014-03-06-p.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.print("hiiiii");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
output.close();
buffer.close();
os.close();
}

Solved:
replace '#' character with '%40' at parse time it will automatically got converted to '#'.
URL url = new URL("ftp://p%40g.com:g%401234#ftp.xyz.com/testjar/2014-03-06-p.txt;type=i");
URLConnection urlc = url.openConnection();
OutputStream os = urlc.getOutputStream(); // To upload
OutputStream buffer = new BufferedOutputStream(os);
PrintStream output = new PrintStream(buffer);
output.print("wowhii");
buffer.close();
os.close();
output.close();

Related

HttpURLConnection: writing into OutputStream, get response

I'm using this answer to write into a HttpURLConnection. It works fine and I close the stream and the connection:
MultipartEntityBuilder mb =
MultipartEntityBuilder.create();//org.apache.http.entity.mime
mb.addTextBody("foo", "bar");
mb.addBinaryBody("bin", new File("testFilePath"));
org.apache.http.HttpEntity e = mb.build();
URLConnection conn = new URL("http://127.0.0.1:8080/app").openConnection();
conn.setDoOutput(true);
conn.addRequestProperty(e.getContentType().getName(),
e.getContentType().getValue());//header "Content-Type"...
conn.addRequestProperty("Content-Length",
String.valueOf(e.getContentLength()));
OutputStream fout = conn.getOutputStream();
e.writeTo(fout);//write multi part data...
fout.close();
conn.getInputStream().close();//output of remote url
just fine. However, I would like to know the server's response (json). How would I do that? I tried using:
InputStream input = conn.getInputStream();
String inputString = new Scanner(input, "UTF-8").useDelimiter("\\Z").next();
input.close();
But I get a java.util.NoSuchElementException error.
In the past I've only used the conn.connect() method and then the conn.getInputStream() and it worked fine. Why it doesn't now? How do I fix that error?

Java UTF-8 encoding not working HttpURLConnection

I tried to do post call and to pass input with this value - "ä€愛لآहที่"
I got error message
{"error":{"code":"","message":{"lang":"en-US","value":{"type":"ODataInputError","message":"Bad Input: Invalid JSON format"}}}}
This is my code
conn.setRequestMethod(ConnectionMethod.POST.toString());
conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(content.getBytes().length));
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(content);
wr.flush();
wr.close();
InputStream resultContentIS;
String resultContent;
try {
resultContentIS = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(resultContentIS));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
it falied on conn.getInputStream();
The value of content is
{ "input" : "ä€愛لآहที่" }
It is working where the input is String or integer
When I added the statement
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
I got different message
{"error":{"code":"","message":{"lang":"en-US","value":{"type":"Error","message":"Internal server error"}}}}
Please try this code below:
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(content);
writer.close();
wr.close();
You should use JSONObject to pass params
The input, please try
BufferedReader reader = new BufferedReader(new InputStreamReader(resultContentIS, "UTF-8"));
If the out put is: ???????, so do not worry because your output console do not support UTF-8
It seems that your variable content does already have the wrong data because you may have converted a String without any attention to the required encoding.
Setting the correct enconding on the writer and use write() instead of writeBytes() should be worth a try.
You have to send content via byte array
DataOutputStream outputStream= new DataOutputStream(conn.getOutputStream());
outputStream.write(content.toString().getBytes());
This is completely solution for your file name character problems. The imported point is string sending via byte array. Every character changing via byte character. This is prevent your character encoding problems.

when servlet receive xml data , there is a error

servelt code
System.out.println(" ================servlet==================");
InputStream in = request.getInputStream();
int a = in.available();
byte[] b = new byte[a];
in.read(b);
String stringValue = new String(b,"utf-8");
System.out.println("receive data==="+stringValue);
OutputStream dataOut = response.getOutputStream();
String responseData = "<test>test</test>";
System.out.println("response datea==="+responseData);
dataOut.write(responseData.getBytes("utf-8"));
dataOut.flush();
dataOut.close();
client code
System.out.println("================client======================");
java.net.URL url = new java.net.URL("test address");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
String sendData = "<data>send</data>";
System.out.println("send data="+sendData);
OutputStream dataOut = con.getOutputStream();
dataOut.write(sendData.getBytes("utf-8"));
dataOut.flush();
dataOut.close();
InputStream in = con.getInputStream();
int a = in.available();
byte[] b = new byte[a];
in.read(b);
String stringValue = new String(b,"utf-8");
in.close();
System.out.println("receive data="+stringValue);
I get the print results
servlet console
================servlet==================
receive data===
response datea===test
client console
================client======================
send data=<data>send</data>
receive data=<test>test</test>
My question is that servlet can't receive the data from the client
who can help me?
My question is that servlet can't receive the data from the client
It may not be the only problem, but this code is completely broken:
int a = in.available();
byte[] b = new byte[a];
in.read(b);
You're assuming that all the data is available right at the start. You should instead be reading from the stream until it runs out of data. Given that you want the result as text, I'd wrap the stream in an InputStreamReader and read from there. For example:
BufferdReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println("Servlet read line: " + line);
}
If you actually want to read it as XML, you should be able to pass the InputStream (or Reader) to an XML parser library to create a DOM.
You should be doing the same thing in the client code too, by the way. Basically:
Never ignore the return value of InputStream.read
Avoid using available(); it's rarely appropriate
Use an InputStreamReader to read text from a stream, rather than constructing it yourself from the bytes
Use an XML API to read XML rather than handling it as raw text
As of now I can see that the value of int b is 0 so it is not reading any data from the input stream.
According to this documentation
available
will always return 0 for InputStream which has been extended byt the
ServletInputStream.
As told by Jon or
Edit:
InputStream is=request.getInputStream();
OutputStream os=response.getOutputStream();
byte[] buf = new byte[1024];
int chunk = is.read(buf);

How Do You Upload a File to a Server With PHP using Java [duplicate]

This question already has answers here:
How to send PUT, DELETE HTTP request in HttpURLConnection?
(8 answers)
Closed 9 years ago.
I have a Java applet that needs to upload a file from the user's computer to the server.
I am unable to add other libraries (such as com.apache). Is there a low level way of doing so.
Currently, I have a php file on the server which contains:
//Sets the target path for the upload.
$target_path = "spelling/";
$_FILES = $_POST;
var_dump($_FILES);
move_uploaded_file($_FILES["tmp_name"], $target_path . $_FILES["name"]);
?>
Currently my Java program is sending parameters via POST to this php file.
It sends these parameters by POST using the following code:
try {
//Creates a new URL containing the php file that writes files on the ec2.
url = new URL(WEB_ADDRESS + phpFile);
//Opens this connection and allows for the connection to output.
connection = url.openConnection();
connection.setDoOutput(true);
//Creates a new streamwriter based on the output stream of the connection.
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
//Writes the parameters to the php file on the ec2 server.
wr.write(data);
wr.flush();
//Gets the response from the server.
//Creates a buffered input reader from the input stream of the connection.
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
//Loops through and reads the response. Loops until reaches null line.
while ((line = rd.readLine()) != null) {
//Prints to console.
System.out.println(line);
}
//Closes reader and writer.
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
This works for POST'ing data but when I try to send a file using this method, nothing happens (no response from the server nor is the file uploaded).
If anyone has any hints I would be grateful :)
Are you using java.net.URLConnection?
You may want to get some help on this page:
http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically
Here is the main part:
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
But, you will need to have the php script be on the same server where your applet came from.

get content from website with utf8 format

i want how to get the content from websites with utf8 format,,
i have writing the following code is
try {
String webnames = "http://pathivu.com";
URL url = new URL(webnames);
URLConnection urlc = url.openConnection();
//BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());
BufferedReader buffer = new BufferedReader(new InputStreamReader(urlc.getInputStream(), "UTF8"));
StringBuilder builder = new StringBuilder();
int byteRead;
while ((byteRead = buffer.read()) != -1)
builder.append((char) byteRead);
buffer.close();
String text=builder.toString();
System.out.println(text);
}
catch (IOException e)
{
e.printStackTrace();
}
but i cant get the correct format...
thanks and advance..
The problem might be that your console or your System.out are not UTF-8.
Try writing this to a file instead
Set the console stream via System.setOut(..)
You may have to use -Dfile.encoding=utf-8 or OutputStreamWriter
Your code looks ok.. the problem here it will be that in server the data will not be in UTF-8 format..

Categories