HTTP发送请求 接收请求方法 

import java.io.IOException; 
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.multipart.StringPart; 
public class Test { 
	public static void THttpClient() throws Exception  
	{ 
		String url = "http://localhost:8080/Pro/servlet/TServlet";     
		 
		PostMethod postMethod = new PostMethod(url);             
		postMethod.setParameter("cyt", "chenyongtu"); 
		postMethod.setParameter("Name", "David"); 
		HttpClient httpClient = new HttpClient(); 
		int status=httpClient.executeMethod(postMethod); 
		String str=postMethod.getResponseBodyAsString(); 
		System.out.println("Byte to String "); 
		System.out.println("["); 
		System.out.println(new String(postMethod.getResponseBody())+"]"); 
	} 
}

Servlet接收 数据 用outPrint打印 返回给 请求的 HTTPClient

import java.io.IOException; 
import java.io.PrintWriter; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
public class Servlet extends HttpServlet { 
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException { 
		 
		String Name=request.getParameter("Name"); 
		String cyt=request.getParameter("cyt"); 
		response.setContentType("text/html;charset=GB2312"); 
		PrintWriter out = response.getWriter(); 
		out.println("---------------------"); 
		out.println("Name:"+Name); 
		out.println("cyt:"+cyt); 
		out.println("---------------------"); 
		out.close(); 
	} 
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException { 
		doGet(request, response); 
	} 
} 


主函数测试 


public class TMain { 
	public static void main(String[] args) throws Exception { 
		Test t=new Test(); 
		t.THttpClient(); 
 
	} 
} 


想利用 此方法传参,但 Servlet 一直接收不到 ,待研究中 


		/* 
		HttpMethodParams params = new HttpMethodParams(); 
		params.setContentCharset("UTF-8"); 
		params.setParameter("cyt", "陈勇士"); 
		params.setParameter("Name", "大卫1"); 
		postMethod.setParams(params); 
		*/ 
		


源代码下载



评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!