HttpClient的Post和Get方法

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();
        }

    }









你可能感兴趣的:(HttpClient的Post和Get方法)