📄 httppostbean.java
字号:
/*
* @(#)HttpPostBean.java 1.01 2005-5-1
*
* Copyright 2005 BeanSoft Studio. All rights reserved.
* PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package studio.beansoft.net;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Hashtable;
/**
* <p>HttpPostBean performs a http post/get action and reads the response from the
* server.</p>
* A sample code to use this Bean:
* <pre>
HttpPostBean httpPostBean = new HttpPostBean();
httpPostBean.setUrl("http://localhost/test.jsp");
httpPostBean.addParameter("name", "beansoft");
httpPostBean.addParameter("email", "beansoftstudio@msn.com");
if(httpPostBean.doPost()) {
System.out.println(httpPostBean.getResponse());
}
</pre>
* Also you can use GET method to send these parameters:
* <pre>httpPostBean.setMethod("get");</pre>
<p>
* The corresponding JSP file content(note: this file does not handling encoding problems):<BR>
<pre>
<%
System.out.println("name=" + request.gerParameter("name") + "<BR>");
System.out.println("email=" + request.gerParameter("email") + "<BR>");
out.println("name=" + request.gerParameter("name") + "<BR>");
out.println("email=" + request.gerParameter("email") + "<BR>");
%>
<pre>
</p>
* @author BeanSoft
* @version 1.0
*/
public class HttpPostBean {
/** The parameters to post */
private Hashtable parameters = new Hashtable();
/** The url to connect to */
private String url;
/** The response from the server when doing a connection operation */
private byte[] response;
/** HTTP form method, POST or GET, default to POST */
private String method = "post";
/**
* Do the post action and read the response from the server.
*
* @return boolean , false if any error occurs.
*/
public boolean doPost() {
if (url == null || url.length() == 0)
return false;
try {
URL url;
URLConnection urlConn;
DataOutputStream printout;
java.io.BufferedReader input;
// URL of HTTP pages which handles the POST action.
url = new URL(getUrl());
boolean isPost = "post".equalsIgnoreCase(getMethod());
String urlGetMethod = getUrl() + "?";
String content = "";// Content to post
Enumeration enum = parameters.keys();
boolean first = true;// Is this the first parameter?
while (enum.hasMoreElements()) {
String key = enum.nextElement().toString();
if (first == false) {
content += "&";
}
if (isPost) {
content += URLEncoder.encode(key, "GB2312")
+ "="
+ URLEncoder.encode(parameters.get(key).toString(),
"GB2312");
} else {
content += key + "=" + parameters.get(key);
}
first = false;
}
if (!isPost) {
urlGetMethod += content;
url = new URL(urlGetMethod);
}
// URL connection channel.
urlConn = url.openConnection();
// Let the run-time system (RTS) know that we want input.
urlConn.setDoInput(true);
// Let the RTS know that we want to do output.
urlConn.setDoOutput(true);
// No caching, we want the real thing.
urlConn.setUseCaches(false);
if (isPost) {
// Specify the content type.
urlConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream());
printout.writeBytes(content);
printout.flush();
printout.close();
}
// Get response data.
setResponse(null); // Clear response string
int data = 0;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
InputStream in = urlConn.getInputStream();
while ((data = in.read()) != -1) {
bout.write(data);
}
setResponse(bout.toByteArray());
in.close();
return true;
} catch (MalformedURLException me) {
// System.err.println("MalformedURLException: " + me.getMessage());
setResponse(("" + me).getBytes());
return false;
} catch (Exception ex) {
System.err.println("Exception: " + ex.getMessage());
setResponse(("" + ex).getBytes());
ex.printStackTrace();
return false;
}
}
/**
* Add a form parameter.
*
* @param key -
* parameter name
* @param value -
* parameter value
*/
public void addParameter(String key, String value) {
if (value == null || value.length() == 0) {
removeParameter(key);
} else {
parameters.put(key, value);
}
}
/**
* Remove a form parameter from the request.
*
* @param key -
* parameter name
*/
public void removeParameter(String key) {
if (key != null) {
parameters.remove(key);
}
}
/**
* Return the URL this bean will connect to.
*
* @return a URL in string format
*/
public String getUrl() {
return url;
}
/**
* Set a URL this bean will connect to.
*
* @param url
* a URL string without form parameters, eg:
* http://www.abc.com/index.jsp , and
* http://www.abc.com/index.jsp?name=value will cause some error
* when u use HTTP GET method.
*/
public void setUrl(String url) {
this.url = url;
}
/**
* Responsed data by server.
*
* @return byte[] - the data
*/
public byte[] getResponse() {
return response;
}
/**
* Set esponsed data by server
*
* @param response -
* byte[], data array
*/
private void setResponse(byte[] response) {
this.response = response;
}
/**
* @return returns the form method.
*/
public String getMethod() {
return method;
}
/**
* @param method
* The form method to set, valid values is {"get", "post"}, null
* value means "post".
*/
public void setMethod(String method) {
this.method = method;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -