HttpClient的Post和Get方法

本文提供了使用Java实现HTTP请求的示例代码,包括GET和POST请求的不同情况,如无参数、带参数等,并展示了如何发送请求及解析响应。

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

1.不带参数的get请求

/**
	 * 不带参数的Get请求
	 */
	public static void doGetWithoutParameter() throws Exception{
		//创建一个HttpClient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
		//创建一个GET对象
		HttpGet httpGet = new HttpGet("http://www.baidu.com");
		
		//执行请求
		CloseableHttpResponse response = httpClient.execute(httpGet);
		
		//获取返回状态(200为成功)
		int statusCode = response.getStatusLine().getStatusCode();
		
		//获取响应的结果(请求返回的结果保存在Entity中)
		HttpEntity entity = response.getEntity();
		String content = EntityUtils.toString(entity,"UTF-8");
		System.out.println(content);
		
		//关闭httpClient
		response.close();
		httpClient.close();
	}

2.带参数的Get请求

/**
	 * 代参数的Get请求
	 */
	public static void doGetWithParameter() throws Exception{
		//创建一个HttpClient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		
	     // 创建URI对象,定义请求的参数
         URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
		
		//创建一个GET对象
		HttpGet httpGet = new HttpGet("http://www.baidu.com");
		
		//执行请求
		CloseableHttpResponse response = httpClient.execute(httpGet);
		
		//获取返回状态(200为成功)
		int statusCode = response.getStatusLine().getStatusCode();
		
		//获取响应的结果(请求返回的结果保存在Entity中)
		HttpEntity entity = response.getEntity();
		String content = EntityUtils.toString(entity);
		System.out.println(content);
		
		//关闭httpClient
		response.close();
		httpClient.close();
	}


3.Post的无参数请求


自己写的服务器程序,用于提供post请求的服务

	@RequestMapping(value="/httpclient/post",method=RequestMethod.POST)
	@ResponseBody 
	public TaotaoResult testPost(){
		
		return TaotaoResult.ok();
	}
对应的请求代码

   // 创建http POST请求
  HttpPost httpPost = new HttpPost("http://localhost:8082/httpclient/post");

完整代码:

public static void doPostWithOutParamater() throws Exception{
	    // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://localhost:8082/httpclient/post");

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }


3.Post的带参数请求

服务器端

这里MediaType可以设置多个值

/**
	 * !!!如果不设置返回的数据会乱码
	 * 设置返回响应数据的数据类型和编码格式
	 * produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8"
	 */
	@RequestMapping(value="/httpclient/post",method=RequestMethod.POST,produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
	@ResponseBody 
	public String testPost(String username,String password){

		return "username:"+username+"   "+"password:"+password;
	}


请求端

/**
	 * 带参数的post
	 */
	public static void doPostWithParamater() throws Exception{
	    // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建http POST请求
        //!!!注意参数不能在URL中添加
        HttpPost httpPost = new HttpPost("http://localhost:8082/httpclient/post");
  
        //创建一个Entity,模拟一个表单
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("username", "张三"));
        parameters.add(new BasicNameValuePair("password", "java"));
        
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"GBK");
       
        //设置请求的内容
        httpPost.setEntity(formEntity);
        
     
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }

    }









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值