📄 messageposter.java
字号:
package com.cxz.httpchat.util;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.StreamException;
/**
*
* @author CXZ
*
* @param <REQ_OBJ>
* @param <RESP_OBJ>
*
* @version 2.0 of MessagePoster
* This Class is used by client to send a post message
*/
public class MessagePoster<REQ_OBJ, RESP_OBJ> {
private String url = "http://localhost:8080/HttpChat/Server";
private String propLoc = "com/cxz/httpchat/util/class.properties";
// The XStream instance is thread-safe.
public XStream xstream = null;
public MessagePoster() {
initXStream();
}
public void setUrl(String url) {
this.url = url;
}
private void initXStream() {
xstream = new XStream();
Properties properties = new Properties();
try {
properties.load(MessagePoster.class.getClassLoader()
.getResourceAsStream(propLoc));
Set keys = properties.keySet();
for (Object key : keys) {
xstream.alias((String) key, Class.forName((String) properties
.get(key)));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public RESP_OBJ postXML(REQ_OBJ requestObj) throws HttpException,
IOException {
RESP_OBJ responseObj = null;
PostMethod method = null;
try {
String xml = xstream.toXML(requestObj);
HttpClient client = new HttpClient();
method = new PostMethod(url);
RequestEntity entity;
entity = new StringRequestEntity(xml, "text/xml", "utf-8");
method.setRequestEntity(entity);
client.executeMethod(method);
responseObj = (RESP_OBJ) xstream.fromXML(method
.getResponseBodyAsStream());
} catch(StreamException e){
e.printStackTrace();
} finally {
method.releaseConnection();
}
return responseObj;
}
public static void main(String[] args) {
// try {
// UploadRequest upload = new UploadRequest();
// upload.setUserId(1);
// upload.setPassword("19841230");
// upload.setType(AbstractMessage.HEART_BEAT_REQUEST);
// upload.setFrom("joanna");
// upload.setContent("Hi");
// upload.setDate(new Date(System.currentTimeMillis()));
// upload.setType(AbstractMessage.UPLOAD_REQUEST);
// upload.setTo(12);
// new MessagePoster<UploadRequest, UploadResponse>().postXML(upload);
// } catch (HttpException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -