方法一:
(原始办法)
/*
* @remark: 获取用户资料
* @param: url发送数据的URL
* @param: param获取用户资料的参数
* @return: 获取用户资料状态信息
*/
String GetUser(String url, String param)
{
URL httpurl = null;
HttpURLConnection httpConn = null;
String line = "";
try
{
httpurl = new URL(url);
httpConn = (HttpURLConnection)httpurl.openConnection();
httpConn.setRequestMethod("POST"); //默认是post
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
PrintWriter outs = new PrintWriter(httpConn.getOutputStream());
outs.print(param);
outs.flush();
outs.close();
BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
while ((line = in.readLine()) != null)
{
if (line.indexOf("#") == -1)
continue;
return line;
}
in.close();
}catch(Exception e)
{
return line;
}
finally
{
if(httpConn!=null)
httpConn.disconnect();
}
return line;
}
该方法写的很简单,不够完善。
方法二:
<%@ page language="java" pageEncoding="GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<%
String name1=request.getParameter("name1");
if(null!=name1){
out.print(name1);out.print("<br>");
}
String name2=request.getParameter("name2");
if(null!=name1){
out.print(name2);out.print("<br>");
}
%>
</body>
</html>
接下来就就是我们的程序部分了:
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
HttpClient client = new HttpClient();
HttpMethod httpPost =getPostMethod();
//HttpMethod httpPost =getGetMethod();
client.getHostConfiguration().setHost("localhost", 8080, "http");
try {
int status = client.executeMethod(httpPost);
if(status==200)
{
System.out.println(httpPost.getResponseBodyAsString());
}
else
{
System.out.println("页面请求返回值为:"+status);
}
} catch (HttpException e) {
e.printStackTrace(System.err);
} catch (IOException e) {
e.printStackTrace(System.err);
}finally{
httpPost.releaseConnection();
}
}
/**
* 使用POST方式提交数据
* @return
*/
private static HttpMethod getPostMethod(){
PostMethod post = new PostMethod("/PostTest/index.jsp");
NameValuePair simcard = new NameValuePair("name1","1330227");
NameValuePair simcard2 = new NameValuePair("name2","kjasdfklalsf");
post.setRequestBody(new NameValuePair[] { simcard,simcard2});
return post;
}
/**
* 使用GET方式提交数据
* @return
*/
private static HttpMethod getGetMethod(){
return new GetMethod("/PostTest/index.jsp?name1=1330227&name2=asdfsdf");
}
}
注意:大家要把commons-codec-1.3.jar,commons-httpclient-3.0.jar,commons-logging.jar这三个JAR包加到我们程序的classpath中,才能使用跑起来.
posted on 2007-12-23 23:38
-274°C 阅读(6469)
评论(5) 编辑 收藏 所属分类:
JAVA