HTTLClient 调用 Servlet 并返回数据

本文介绍如何使用HTTPLient库发送HTTP请求到Servlet,并尝试从Servlet接收数据。目前遇到的问题是Servlet无法接收到传递的参数,作者正在进行深入研究。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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


源代码下载


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值