1 5 package org.exoplatform.services.communication.sms.util; 6 7 import java.io.ByteArrayInputStream ; 8 import java.io.IOException ; 9 import java.io.InputStream ; 10 import java.net.URL ; 11 12 import org.apache.commons.httpclient.Header; 13 import org.apache.commons.httpclient.HttpClient; 14 import org.apache.commons.httpclient.HttpException; 15 import org.apache.commons.httpclient.HttpStatus; 16 import org.apache.commons.httpclient.NameValuePair; 17 import org.apache.commons.httpclient.methods.PostMethod; 18 import org.exoplatform.services.communication.sms.common.CommunicationError; 19 20 21 25 public class ClientHttpSocket { 26 27 private String _host; 28 private int _port; 29 private String _username; 30 private String _password; 31 32 public ClientHttpSocket(String host, int port, String username, String password) { 33 _host = host; 34 _port = port; 35 _username = username; 36 _password = password; 37 } 38 39 43 public String sendMessage(String payload) throws CommunicationError { 44 String response = ""; 45 HttpClient client = new HttpClient(); 46 InputStream stream = new ByteArrayInputStream (payload.getBytes()); 47 try { 48 URL url = new URL ("http", _host, _port, "/sms"); 49 PostMethod post = new PostMethod(url.toString()); 50 try { 51 post.addRequestHeader(new Header("Content-type", " application/xml")); 52 post.addParameter(new NameValuePair("user", _username)); 53 post.addParameter(new NameValuePair("pw", _password)); 54 post.setRequestBody(stream); 55 56 client.executeMethod(post); 57 if (post.getStatusCode() == HttpStatus.SC_OK) { 58 response = post.getResponseBodyAsString(); 59 } else { 60 throw new CommunicationError("Unexpected failure: " + post.getStatusLine().toString()); 61 } 62 } finally { 63 post.releaseConnection(); 64 } 65 stream.close(); 66 } catch (HttpException e) { 67 throw new CommunicationError(e); 68 } catch (IOException e) { 69 throw new CommunicationError(e); 70 } 71 return response; 72 } 73 74 } | Popular Tags |