java post 请求 设置head

第一种:

     /**
     * url: 请求地址
     * param: 请求参数 [{'key1':'value1','key2':'value2'},{'key1':'value3','key2':'value4'}]  
     * header 设置header
     * 
     */
	public static String sendPost(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
	        PrintWriter out = null;
	        BufferedReader in = null;
	        String result = "";
	        URL realUrl = new URL(url);
	        // 打开和URL之间的连接
	        URLConnection conn = realUrl.openConnection();
	        //设置超时时间
	        conn.setConnectTimeout(5000);
	        conn.setReadTimeout(15000);
	        // 设置通用的请求属性
	        if (header!=null) {
	            for (Entry<String, String> entry : header.entrySet()) {
	                conn.setRequestProperty(entry.getKey(), entry.getValue());
	            }
	        }
	        conn.setRequestProperty("accept", "*/*");
	        conn.setRequestProperty("connection", "Keep-Alive");
	        conn.setRequestProperty("user-agent",
	                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
	        // 发送POST请求必须设置如下两行
	        conn.setDoOutput(true);
	        conn.setDoInput(true);
	        // 获取URLConnection对象对应的输出流
	        out = new PrintWriter(conn.getOutputStream());
	        // 发送请求参数
	        out.print(param);
	        // flush输出流的缓冲
	        out.flush();
	        // 定义BufferedReader输入流来读取URL的响应
	        in = new BufferedReader(
	                new InputStreamReader(conn.getInputStream(), "utf8"));
	        String line;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	        if(out!=null){
	            out.close();
	        }
	        if(in!=null){
	            in.close();
	        }
	        return result;
	    }

第二种:

/**
     * url: 请求地址
     * param: 请求参数 [{'key1':'value1','key2':'value2'},{'key1':'value3','key2':'value4'}]  
     * 
     */
    public static void postParams(String url, String param) {
    	// 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String entityStr = null;
        CloseableHttpResponse response = null;
        try {
            // 创建POST请求对象
            HttpPost httpPost = new HttpPost(url);
            // 创建请求参数
            StringEntity entityParam = new StringEntity(param, Charset.forName("UTF-8"));
            httpPost.setEntity(entityParam);
            // 浏览器表示
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
            // 传输的类型
            httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
            
            httpPost.addHeader("accept", "*/*");
            httpPost.addHeader("connection", "Keep-Alive");
     
            // 执行请求
            response = httpClient.execute(httpPost);
            // 获得响应的实体对象
            HttpEntity entity = response.getEntity();
            // 使用Apache提供的工具类进行转换成字符串
            entityStr = EntityUtils.toString(entity, "UTF-8");
     
        } catch (ClientProtocolException e) {
            System.err.println("Http协议出现问题");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO异常");
            e.printStackTrace();
        } finally {
            // 释放连接
            if (null != response) {
                try {
                    response.close();
                    httpClient.close();
                } catch (IOException e) {
                    System.err.println("释放连接出错");
                    e.printStackTrace();
                }
            }
        }
        // 打印响应内容
        System.out.println(entityStr);
    }

记录一下,以便下次使用

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值