Here is the code I am trying to send SMS through the red Oxygen server
Here is the code I am executing below
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
DataOutputStream output = null;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeBytes(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
While executing I am getting the below exception :
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:525)
at sun.net.NetworkClient.doConnect(NetworkClient.java:158)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:860)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:801)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:726)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:904)
at com.nextenders.server.LoginServlet.SendSMS(LoginServlet.java:143)
I tried with increasing connection timeout and turn off the firewall ...etc but no luck .Can anyone help me to trace the problem ??
Here is the tutorial I'm following :
http://www.redoxygen.com/developers/java/
The "*"s in my code is credentials for the gateway .
This is a network topology problem. You can't connect to that site from where you are. Some intervening firewall, probably your own, is preventing it. Talk to your netadmin.
The following code runs fine when I have tested it with other websites (as I don't have access your the messaging API):
final String requestURL = "http://www.redoxygen.net/sms.dll?Action=SendSMS";
final StringBuilder stringBuilder = new StringBuilder();
try {
stringBuilder.append("AccountId=").append(URLEncoder.encode("****", "UTF-8"))
.append("&Email=").append(URLEncoder.encode("*******", "UTF-8"))
.append("&Password=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Recipient=").append(URLEncoder.encode("******", "UTF-8"))
.append("&Message=").append(URLEncoder.encode("hello", "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
final URL address;
try {
address = new URL(requestURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
final HttpURLConnection connection;
try {
connection = (HttpURLConnection) address.openConnection();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
connection.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setConnectTimeout(100000000);
try {
connection.connect();
} catch (IOException e) {
throw new RuntimeException(e);
}
final DataOutputStream output;
try {
output = new DataOutputStream(connection.getOutputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
output.writeUTF(stringBuilder.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
final InputStream inputStream;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(connection.getErrorStream(), "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println("Error response code from server. Error was:");
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
throw new RuntimeException(e);
}
final char[] buffer = new char[0x10000];
final StringBuilder stackBuilder = new StringBuilder();
final Reader in;
try {
in = new InputStreamReader(inputStream, "UTF-8");
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
try {
int read;
do {
read = in.read(buffer, 0, buffer.length);
if (read > 0) {
stackBuilder.append(buffer, 0, read);
}
} while (read >= 0);
System.out.println(stackBuilder.toString());
} catch (IOException ex) {
throw new RuntimeException(ex);
} finally {
try {
in.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
It will toString the various streams and has error handling when the stream doesn't connect.
The most important change is using the DataOutputStream.writeUTF method rather than just the write method - this will ensure than the POST data is encoded correctly. I don't think this is your issue as the problem is on connect.
The example code you used seems to be unaware of Java naming conventions or best practices to I have tidied it considerably.
The stream reader can be pulled out and into a separate method to avoid duplication.
I would recommend pointing it at another website (I used my work's) and seeing if you get output.
Related
I am uploading a file from one server to another server using a Java Program 'POST' method. But I am getting below exception.
java.io.IOException: Error writing to server
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:582)
at sun.net.www.protocol.http.HttpURLConnection.writeRequests(HttpURLConnection.java:594)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1216)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
at com.test.rest.HttpURLConnectionExample.TransferFile(HttpURLConnectionExample.java:107)
at com.test.rest.HttpURLConnectionExample.main(HttpURLConnectionExample.java:44)
I have other method who will authenticate with server. Which will be be called from below code. When I am getting response from server, I am getting above exception. To Transfer a file to server I have written below method. My sample code is below:
public static void TransferFile(){
String urlStr = "http://192.168.0.8:8600/audiofile?path=1/622080256/virtualhaircut.mp3";
File tempFile = new File("/home/MyPath/Workspace/Sample/virtualhaircut.mp3");
BufferedWriter br=null;
HttpURLConnection conn = null;
URL url;
try {
url = new URL(urlStr);
AuthenticationUser();
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", new MimetypesFileTypeMap().getContentType(tempFile.getName()));
} catch (MalformedURLException e1) {
System.out.println("Malformed");
e1.printStackTrace();
} catch (ProtocolException e) {
System.out.println("Protocol");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO");
e.printStackTrace();
}
System.out.println("line 69");
FileInputStream fis;
OutputStream fos;
try {
System.out.println("line 75");
System.out.println("line 77");
fis = new FileInputStream(tempFile);
fos = conn.getOutputStream();
byte[] buf = new byte[1024 * 2];
int len = 0;
System.out.println("line 80");
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
System.out.println("line 85");
}
System.out.println("line 87");
buf = null;
fos.flush();
fos.close();
fis.close();
}catch (FileNotFoundException e) {
System.out.println("");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (conn.getResponseCode() == 200) {
System.out.println("here");
}
} catch (IOException e) {
e.printStackTrace();
}
}
It is possible that the error ocurred because the receiving server closed the connection, maybe because your file exceeded the size limit. Have you tested with small files?
I have a problem with gae. I have an application http://www.similarityface.appspot.com/query. I am trying through a program in java to communicate with this application to perform query, via the POST method. The problem that is generating 500 error.
The code is below, could someone help me telling what I'm doing wrong.
public class Vetores_Facebook {
public static void main(String[] args) throws UnsupportedEncodingException, IOException {
final String server = "https://www.similarityface.appspot.com/query";
URL url = null;
try {
url = new URL(server);
} catch (MalformedURLException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
HttpURLConnection urlConn = null;
try {
// URL connection channel.
urlConn = (HttpURLConnection) url.openConnection();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
urlConn.setDoOutput (true);
// No caching, we want the real thing.
urlConn.setUseCaches (false);
try {
urlConn.setRequestMethod("POST");
} catch (ProtocolException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
writer.write(message);
writer.close();
}
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("ok");
}
else{
int x = urlConn.getResponseCode();
System.out.println("error "+x);
}
}
}
try {
urlConn.connect();
} catch (IOException ex) {
Logger.getLogger(Vetores_Facebook.class.getName()).log(Level.SEVERE, null, ex);
}
String message = URLEncoder.encode("get_object(\"me\", metadata=1)", "UTF-8");
try (OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream())) {
writer.write(message);
writer.close();
}
The problem is you are calling urlConn.connect(); which seems to flush any output buffers you may have and prepares the connection to get an input stream. Trying to write to open an output stream after this will cause an exception.
Use the example given here for the correct way to do this: https://developers.google.com/appengine/docs/java/urlfetch/usingjavanet#Using_HttpURLConnection
My idea is that I want to read an object from a serialized file located in a server. How to do that?
I can only read .txt file using the following code :
void getInfo() {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://localhost/Test.txt");
// Note: a more portable URL:
//url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
} catch (MalformedURLException mue) {
System.out.println("Error!!!");
} catch (IOException ioe) {
System.out.println("Error!!!");
}
}
You can do this with this method
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.
To write an object to the file there's another method
public void serialize(Object obj, String fileName) {
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
AM trying to download a file from the net using the url & urlconnection class in java using this code.
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(destination);
} catch (FileNotFoundException ex) {
}
try {
URL url = null;
try {
url = new URL("here is the url");
//
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
URLConnection urlc = null;
try {
urlc = url.openConnection();
System.out.println("Conneceted");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
bis = new BufferedInputStream(urlc.getInputStream());
} catch (IOException ex) {
ex.printStackTrace();
}
bos = new BufferedOutputStream(fos);
// System.out.println("absolute path="+destination.getAbsolutePath());
int i;
try {
while ((i = bis.read()) != -1) {
System.out.print((char) i);
bos.write(i);
}
JOptionPane.showMessageDialog(this, "downloadeded sucessfully");
this.dispose();
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "could not be diownloaded \n please try again");
ex.printStackTrace();
}
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
When i run this code on my windows system it runs perfectly but when i take my code to mac os it gives me the exception
Exception in thread "Thread-2" java.lang.NullPointerException
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at java.io.FilterOutputStream.close(FilterOutputStream.java:140)
at FileDownloader.Download(FileDownloader.java:201)
at FileDownloader$2.run(FileDownloader.java:114)
at java.lang.Thread.run(Thread.java:637)
Could anyone tell me what the reason may be? and how i can solve this?
Thanks in advance
I have two methods, one that serialize the Object, and it works ok:
public void record()throws RecordingException
{
ObjectOutputStream outputStream = null;
try
{
outputStream = new ObjectOutputStream(new FileOutputStream("src/data/employee.dat"));
outputStream.writeObject(this);
} catch (FileNotFoundException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
} catch (IOException ex)
{
ex.printStackTrace();
throw new RecordingException(ex);
}finally
{
try
{
if (outputStream != null) outputStream.close();
} catch (IOException ex){}
}
}
The problem here when deserializing the object, I get EOFException!:
public final User loadObject(UserType usertype) throws InvalidLoadObjectException
{
ObjectInputStream istream = null;
String path = null;
if (usertype == UserType.EMPLOYEE)
{
path = "data/employee.dat";
}else if (usertype == UserType.CUSTOMER)
{
path = "data/customer.dat";
}else
throw new InvalidLoadObjectException("Object is not a sub class of User");
try
{
istream = new ObjectInputStream(ObjectLoader.class.getClassLoader().getResourceAsStream(path));
User u = loadObject(istream);
istream.close();
return u;
}catch (EOFException ex)
{
System.out.println(ex.getMessage());
return null;
}catch(Exception ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
private User loadObject(ObjectInputStream stream) throws InvalidLoadObjectException
{
try
{
return (User) stream.readObject();
} catch (IOException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
} catch (ClassNotFoundException ex)
{
ex.printStackTrace();
throw new InvalidLoadObjectException(ex);
}
}
I don't know if this is the cause of your problem, but the code that writes the file has a subtle flaw. In the finally block, you close the stream and ignore any exceptions. If the close() method performs a final flush(), then any exceptions thrown in the flush will go unreported.
Try outputStream.flush() before closing your stream in serialization object.
The file was empty, or didn't contain the full serialization of the object.