java原生http请求

最近搞了一个没有Maven的项目,全都是Jar包,我接手后也没改变原有的架构,也懒得百度找Jar包,就手写了一个原生的http请求,以后有需要我在回来拷贝!!!!!!!!!!

其实还可以加个字符串转对象的方法,考虑到并不是所有平台返回的数据都是json格式,所以就没写....

 public static void main(String[] args) throws Exception {
        Map<String,String> map = new HashMap<String,String>(16);
        map.put("access_token","xxxxxxxxxxxx");
        map.put("url","xxxxxxxx");
        map.put("baike_num","xx");
        System.out.println(post("https://aip.baidubce.com/rest/2.0/image-classify/v1/plant",map));
    }

    /**
     *  原生http请求
     * @param sendUrl 请求的Url
     * @param map 传入的参数
     * @return
     */
    public static String post(String sendUrl, Map<String,String> map){
        String result="";
        URL url;
        HttpURLConnection conn;
        try{
            url = new URL(sendUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            //连接主机的超时时间(单位:毫秒)
            conn.setConnectTimeout(10000);
            //从主机读取数据的超时时间(单位:毫秒)
            conn.setReadTimeout(10000);
            //设置请求方式
            conn.setRequestMethod("POST");
            //设置  网络文件的类型和网页的编码
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
            int responseCode = conn.getResponseCode();
            if (responseCode > 200 ){
                StringBuffer resultBuffer = new StringBuffer();
                String tempLine = null;
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
                while ((tempLine = bufferedReader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                }
                throw new Exception( "HTTP Request is not success, Response code is " + responseCode + ", And Response message is " + resultBuffer.toString());
            }
            //将数据写入流中
            out.write(mapToString(map));
            //刷新流中的数据
            out.flush();
            //关闭流(关闭之前要先刷新)
            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            //读一行文字并返回该行字符
            while ((line = in.readLine()) != null) {
                result += line;
            }
            return result;
        }
        catch(Exception e){
            e.printStackTrace();
        }finally{
            url=null;
            conn=null;
        }
        return result;
    }

    /**
     * 将map转String
     * @param map
     * @return
     */
    private static String mapToString(Map<String, String> map) {
        StringBuilder sb = new StringBuilder();
        int index = 0;
        for (String i:map.keySet()){
            index ++;
            if (map.size() == index){
                sb.append(i+"="+map.get(i));
            }else {
                sb.append(i+"="+map.get(i)+"&");
            }
        }
        return  sb.toString();
    }

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值