后台支持tomcat,weblogic,resin等.

/* 
* @(#)HttpPostBean.java 1.01 2005-5-1
*
* Copyright 2005 ~ 2013 BeanSoft.biz.
* This class is free to modify or redistricute without any limitations.
*/


 

package 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;


 



/** 
*

HttpPostBean performs a http post/get action and reads the response from the

*  server.

 

* A sample code to use this Bean:
*


 

HttpPostBean httpPostBean = new HttpPostBean();


 

httpPostBean.setUrl("http://localhost/test.jsp");
httpPostBean.addParameter("name", "beansoft");
httpPostBean.addParameter("email", "beansoftstudio@msn.com");
httpPostBean.setEncoding("UTF-8");


 

if(httpPostBean.doPost()) {
System.out.println(httpPostBean.getResponse());
}
* Also you can use GET method to send these parameters:
*
httpPostBean.setMethod("get");


 

* The corresponding JSP file content(note: this file does not handling encoding problems):


 

System.out.println("name=" + request.gerParameter("name") + "
");
System.out.println("email=" + request.gerParameter("email") + "
");
out.println("name=" + request.gerParameter("name") + "
");
out.println("email=" + request.gerParameter("email") + "
");
%>


 





 

* @author BeanSoft
* @version 1.0
*/


 

public class HttpPostBean {
/** The character encoding used to encode parameters. */
private String encoding = "UTF-8";


 

/** 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;


 

// URL of HTTP pages which handles the POST action.
url = new URL(getUrl());


 

boolean isPost = "post".equalsIgnoreCase(getMethod());


 

// If there is always a ? in url, then do not append it to the address again
String urlGetMethod = getUrl().indexOf("?") == -1 ? getUrl() + "?" : getUrl();


 

String content = "";// Content to post


 

Enumeration enumeration = parameters.keys();


 

boolean first = true;// Is this the first parameter?
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement().toString();


 

if (first == false) {
content += "&";
}


 

// if (isPost) {
// content += URLEncoder.encode(key, getEncoding())
// + "="
// + URLEncoder.encode(parameters.get(key).toString(),
// getEncoding());
// } else {
// content += key + "=" + parameters.get(key);
// }
content += URLEncoder.encode(key, getEncoding())
+ "="
+ URLEncoder.encode(parameters.get(key).toString(),
getEncoding());


 

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;
}


 

/** 
* Default encoding is UTF-8.
* @return returns encoding.
*/
public String getEncoding() {
return encoding;
}


 

/** 
* Default encoding is UTF-8.
* @param encoding The encoding to set.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
}

Supports backend server such as tomcat,weblogic,resin etc.



 

/* 
* @(#)HttpPostBean.java 1.01 2005-5-1
*
* Copyright 2005 ~ 2013 BeanSoft.biz.
* This class is free to modify or redistricute without any limitations.
*/


package 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;




/** 
*

HttpPostBean performs a http post/get action and reads the response from the

*  server.
* A sample code to use this Bean:
*


 

HttpPostBean httpPostBean = new HttpPostBean();


httpPostBean.setUrl("http://localhost/test.jsp");
httpPostBean.addParameter("name", "beansoft");
httpPostBean.addParameter("email", "beansoftstudio@msn.com");
httpPostBean.setEncoding("UTF-8");


if(httpPostBean.doPost()) {
System.out.println(httpPostBean.getResponse());
}
* Also you can use GET method to send these parameters:
*
httpPostBean.setMethod("get");


 

* The corresponding JSP file content(note: this file does not handling encoding problems):


 

System.out.println("name=" + request.gerParameter("name") + "
");
System.out.println("email=" + request.gerParameter("email") + "
");
out.println("name=" + request.gerParameter("name") + "
");
out.println("email=" + request.gerParameter("email") + "
");
%>


 





* @author BeanSoft
* @version 1.0
*/


public class HttpPostBean {
/** The character encoding used to encode parameters. */
private String encoding = "UTF-8";


 

/** 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;


// URL of HTTP pages which handles the POST action.
url = new URL(getUrl());


boolean isPost = "post".equalsIgnoreCase(getMethod());


// If there is always a ? in url, then do not append it to the address again
String urlGetMethod = getUrl().indexOf("?") == -1 ? getUrl() + "?" : getUrl();


String content = "";// Content to post


Enumeration enumeration = parameters.keys();


boolean first = true;// Is this the first parameter?
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement().toString();


if (first == false) {
content += "&";
}


// if (isPost) {
// content += URLEncoder.encode(key, getEncoding())
// + "="
// + URLEncoder.encode(parameters.get(key).toString(),
// getEncoding());
// } else {
// content += key + "=" + parameters.get(key);
// }
content += URLEncoder.encode(key, getEncoding())
+ "="
+ URLEncoder.encode(parameters.get(key).toString(),
getEncoding());


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;
}


/** 
* Default encoding is UTF-8.
* @return returns encoding.
*/
public String getEncoding() {
return encoding;
}


/** 
* Default encoding is UTF-8.
* @param encoding The encoding to set.
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
}

转载请注明:WebLogic Android 博客 » [Java进行远程POST/GET操作 HttpPostBean.java

Java do remote POST/GET operation HttpPostBean.java

](http://www.beansoft.biz/2013/04/06/java%e8%bf%9b%e8%a1%8c%e8%bf%9c%e7%a8%8bpostget%e6%93%8d%e4%bd%9c-httppostbean-java/)