Http请求POST,GET,DELETE,UPDATE的实现,以及文件上传

  /**
     * doGet
     *
     * @param
     * @return
     */
    public static String doGet(String url, String UserName, String PassWord) {
        //创建httpclient对象
        HttpClient httpClient = new HttpClient();
        //创建GetMethod方法对象并且给定url
        GetMethod getMethod = new GetMethod(url);

        //权限验证
        String auth = UserName + ":" + PassWord;     
        String code = new sun.misc.BASE64Encoder().encode(auth.getBytes());
        //设置请求头编码
        getMethod.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        //设置请求头的权限认证
        getMethod.setRequestHeader("Authorization", "Basic " + code);
        String response = "";
        String ts = "";
        
        try {
            //创建对象用来接收提交后返回的状态码
            int statusCode = httpClient.executeMethod(getMethod);
            //打印状态码
            //判断访问的状态码
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: " + getMethod.getStatusLine());
                return response;
            }
            // 读取 HTTP 响应内容,打印网页内容
            InputStream responseBody = getMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody, ContentEncoding));

            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            ts = stringBuffer.toString();


            // 读取为字节数组
            //   response = new String(responseBody, ContentEncoding);
        } catch (HttpException e) {
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            logger.error("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            logger.error("发生网络异常!");
            e.printStackTrace();
        } finally {
            //释放连接
            getMethod.releaseConnection();
        }
        return ts;
    }





 /**
     * doDelete
     *
     * @param
     * @return
     */
    public static String doDelete(Integer id, String url) {
        //创建对象接收访问状态的状态码
        String data = "";
        //创建httpclient对象
        HttpClient httpClient = new HttpClient();
        
        httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ContentEncoding);
        //创建delete方法对象
        DeleteMethod method = null;
        //创建code对象进行权限认证
        String code = throughHttp();
        try {
            method = new DeleteMethod();
            //设置url
            method.setURI(new URI(url));
            //添加响应头并且传入加密信息
            method.setRequestHeader("Authorization", "Basic " + code);
            //创建状态code执行delete请求
            int statusCode = httpClient.executeMethod(method);
           
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) {
                return data;
            }
            data = new String(method.getResponseBody(), ContentEncoding);
        } catch (HttpException e) {
            e.printStackTrace();
            logger.error("Please check your provided http address!");
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            if (method != null)
                method.releaseConnection();
        }
        return data;
    }



/**
     * doPut
     *
     * @param
     * @param jsonObj
     * @return
     */
    public static String doPut(String url, String jsonObj) {
        //设置参数
        String resStr = "";
        //创建httpclient对象
        HttpClient htpClient = new HttpClient();
        //创建put提交方法对象
        PutMethod putMethod = new PutMethod(url);
        //创建code调用加密方法
        String code = throughHttp();
        //增加请求头用于处理乱码
        putMethod.addRequestHeader("Content-Type", "application/json");
        //增加权限认证
        putMethod.addRequestHeader("Authorization", "Basic " + code);
    
        putMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ContentEncoding);
        //设置请求主体,并且参数设为json格式
        putMethod.setRequestBody(jsonObj);
        try {
            
            int statusCode = htpClient.executeMethod(putMethod);
            //打印http状态码
            //判断访问的状态码
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: " + putMethod.getStatusLine());
                return resStr;
            }
            //接收相应主体
            byte[] responseBody = putMethod.getResponseBody();
            //处理乱码
            resStr = new String(responseBody, ContentEncoding);
            //打印相应结果
        } catch (Exception e) {
            logger.error(" failed: " + e.getMessage());
            e.printStackTrace();
        } finally {
            putMethod.releaseConnection();
        }
        return resStr;
    }



 /**
     * doPost
     *
     * @param
     * @param jsonObj
     * @return
     */
    public static String doPost(String jsonObj, String url) {
        
        String code = throughHttp();
        //创建client对象
        DefaultHttpClient client = new DefaultHttpClient();
        //创建post方法
        HttpPost post = new HttpPost(url);
        //设置请求头编码
        post.setHeader("Content-Type", "application/json; charset=UTF-8");
        //设置请求头的权限认证
        post.addHeader("Authorization", "Basic " + code);
     
        String response = "";
        try {
            //设置参数格式
            StringEntity stringEntity = new StringEntity(jsonObj, "UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            
            post.setEntity(stringEntity);
           
            HttpResponse res = client.execute(post);
           
            int statusCode = res.getStatusLine().getStatusCode();
            //打印http请求状态
            //判断访问的状态码
            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT) {
                logger.error("Method failed: " + res.getStatusLine());
                return response;
            }
            response = EntityUtils.toString(res.getEntity());// 返回json格式:
            //打印返回数据
        } catch (Exception e) {
            logger.error(" failed: " + e.getMessage());
            e.printStackTrace();
        }
        return response;
    }




    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String upload(File file) {
        String token = "";
        String code = throughHttp();
        // Configure and open a connection to the site you will send the request
        try {
            //链接服务器短的url
            URL url = new URL(RedmineUrlUtil.getRedmineUrl() + "uploads.json");
            //打开url
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //打开输入流
            connection.setDoInput(true);
            //打开输出流
            connection.setDoOutput(true);
            //链接的提交方式
            connection.setRequestMethod("POST");
            // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型
            connection.setRequestProperty("content-type", "application/octet-stream;charset=utf-8");
            //权限认证
            connection.setRequestProperty("Authorization", "Basic " + code);
            // 得到请求的输出流对象
            BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
            // 把数据写入请求的Body
            FileInputStream fileInputStream = new FileInputStream(file);
            //创建字节数组对象并且设定最大范围
            byte[] bytes = new byte[1024];
            int numReadByte = 0;
            while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
                out.write(bytes, 0, numReadByte);
            }
            //刷新
            out.flush();
            //释放资源
            fileInputStream.close();
            out.close();
            // 从服务器读取响应
            InputStream inputStream = connection.getInputStream();
            String encoding = connection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);
            //创建mapper用来解析json格式数据
            ObjectMapper mapper = new ObjectMapper();
            UploadResultBean uploudResult = mapper.readValue(body, UploadResultBean.class);
            token = uploudResult.getUpload().getToken();
            return token;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            return token;
        }
    }


 /**
     * 权限认证:用户名和密码(有的可能不需要)
     *
     * @return
     */
    public static String throughHttp() {
        //定义用户名和密码
        String auth = RedmineCodeUtil.getUsername() + ":" + RedmineCodeUtil.getPassword();
        //对账号和密码进行加密
        String code = new sun.misc.BASE64Encoder().encode(auth.getBytes());
        //返回code
        return code;
    }




    /**
     * description:将map转换成url参数格式: name1=value1&name2=value2
     *  用于Get请求url参数
     * @param map
     * @return
     */
    private static Logger logger = Logger.getLogger(RedmineApi.class);
    public static String getUrlParamsFromMap(Map map) {
        try {
            if (null != map) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry entry : map.entrySet()) {
                    stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=")
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8")).append("&");
                }
                String content = stringBuilder.toString();
                if (content.endsWith("&")) {
                    content = StringUtils.substringBeforeLast(content, "&");
                }
                return content;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }
}

 

你可能感兴趣的:(Http请求POST,GET,DELETE,UPDATE的实现,以及文件上传)