使用HttpClient发送POST请求

这篇博客展示了如何在Java中使用HttpClient库发送POST请求。通过创建NameValuePair对象填充参数,构建UrlEncodedFormEntity,然后在HttpPost对象中设置请求实体。最后,利用HttpClients创建HttpClient实例,执行请求并获取响应内容。

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

java代码的客户端
package com.xp.android.httpclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientUtils {
	//使用HttpClient发送POST请求
	public static String httpClientPost(String url,Map<String, String> param,String encode){
		
		String result = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		if(param != null && !param.isEmpty()){
			for (Map.Entry<String, String> entry:param.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
				list.add(pair);
			}
		}
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,encode);
			HttpPost post = new HttpPost(url);
			post.setEntity(entity);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(post);
			HttpEntity responseEntity = response.getEntity();
			if(responseEntity!=null){
				InputStream inputStream = responseEntity.getContent();
				result = inputStreamToString(inputStream, encode);
				if(inputStream != null){
					inputStream.close();
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(httpclient != null){
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	//将输入流读取的数据转换成字符串
	public static String inputStreamToString(InputStream inStream,String encString) throws IOException{
		String result = null;
		byte[] data = new byte[1024];
		int len = 0;
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		while((len = inStream.read(data))!=-1){
			outputStream.write(data, 0, len);
		}
		result = new String(outputStream.toByteArray(), encString);
		return result;	
	}
	
	
	public static void main(String args[]){
		String url = "http://localhost:8080/HttpDemo/httpdemo";
		Map<String, String> param = new HashMap<String, String>();
		param.put("name", "zhangsan");
		param.put("pwd", "123");
		String result = httpClientPost(url, param, "utf-8");
		System.out.println("result = " + result);
	}
}
HttpClient依赖的jar包如下  可以从 http://hc.apache.org/downloads.cgi 下载一个版本包 其中包括了使用指南等<img src="https://img-blog.youkuaiyun.com/20151022201731162?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
web端使用servlet来实现的
<pre name="code" class="java">package com.xp.android;

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 HttpDemoServlet extends HttpServlet{

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		super.service(request, response);
		request.setCharacterEncoding("utf-8");
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		System.out.println("name="+name);
		System.out.println("pwd="+pwd);
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		if(name.equals("zhangsan")&&pwd.equals("123")){
			out.print("login success!");
		}else{
			out.print("login error!");
		}
		out.flush();
		out.close();
	}
	
	
}





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值