Http网络请求工具类

public class HttpUtil
{
    /**
     * 获取网络图片
     *
     * @param    imageurl   图片网络地址
     * @return   Bitmap     返回网络上下载的图片
     */
    public static Bitmap getBitmapFromNet(String imageurl)
    {
        URL url;
        HttpURLConnection connection=null;
        Bitmap bitmap=null;
        try
        {
            url = new URL(imageurl);
            connection=(HttpURLConnection)url.openConnection();
            connection.setConnectTimeout(6000); //超时设置
            connection.setDoInput(true);
            connection.setUseCaches(false); //设置不使用缓存
            InputStream inputStream=connection.getInputStream();
            bitmap= BitmapFactory.decodeStream(inputStream);
            inputStream.close();
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 获取网络 字符串
     *
     * @param    address   后台提供的接口
     * @return   String
     */
    public static String getStringFromNet(final String address)
    {
        HttpURLConnection connection = null;
        try
        {
            URL url = new URL(address);

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", UrlHelper.getUA());
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.getDoInput();
            connection.getDoOutput();

            InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            StringBuffer response = new StringBuffer();
            String line = new String();

            while ((line = reader.readLine()) != null)
            {
                response.append(line);
            }
            try
            {
                if(in != null)
                {
                    in.close();
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            return response.toString();
        }
        catch (Exception e)
        {
            return null;
        }
        finally
        {
            if(connection != null)
            {
                connection.disconnect();
            }
        }
    }

    /**
     * 向网络 发送字符串
     *
     * @param    address   后台提供的接口
     * @return   String
     */
    public static String sendStrToNet(String address, String Json)
    {
        String result = "";
        BufferedReader reader = null;
        try
        {
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Charset", "UTF-8");
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
            // 设置接收类型否则返回415错误
            //conn.setRequestProperty("accept","*/*")此处为暴力方法设置接受所有类型,以此来防范返回415;
            conn.setRequestProperty("accept","application/json");
            // 往服务器里面发送数据
            if (Json != null && !(Json != null))
            {
                byte[] writebytes = Json.getBytes();
                // 设置文件长度
                conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
                OutputStream outwritestream = conn.getOutputStream();
                outwritestream.write(Json.getBytes());
                outwritestream.flush();
                outwritestream.close();
            }
            if (conn.getResponseCode() == 200)
            {
                reader = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                result = reader.readLine();
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 向网络发送图片
     *
     * @param    urlHost   上传地址
     * @param    bitmap    上传的图片
     * @param    key       图片名
     *
     * @return   String    返回码/上传是否成功
     */

    public static String sendBitmapToNet(String urlHost, Bitmap bitmap, String key)
    {
        byte[] imageBytes = ChByteUtil.Bitmap2Bytes(bitmap);
        String endString = "\r\n";
        String twoHyphen = "--";
        String boundary = "*****";
        try
        {
            URL url = new URL(urlHost);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", ChUrlHelper.getUA());
            //con.setRequestProperty("content-type", "text/html");
            //允许input、Output,不使用Cache
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            //设置传送的method=POST
            connection.setRequestMethod("POST");

            //setRequestProperty
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            //设置DataOutputStream
            DataOutputStream dsDataOutputStream = new DataOutputStream(connection.getOutputStream());
            dsDataOutputStream.writeBytes(twoHyphen + boundary + endString);
            dsDataOutputStream.writeBytes("Content-Disposition:form-data;" + "name=\"" + key + "\";filename=\"" +
                    "11.jpg\"" + endString);
            dsDataOutputStream.writeBytes(endString);

            //取得文件的FileInputStream
            dsDataOutputStream.write(imageBytes, 0, imageBytes.length);

            dsDataOutputStream.writeBytes(endString);
            dsDataOutputStream.writeBytes(twoHyphen + boundary + twoHyphen + endString);

            dsDataOutputStream.close();

            int cah = connection.getResponseCode();
            if (cah == 200)
            {
                InputStream isInputStream = connection.getInputStream();
                int ch;
                StringBuffer buffer = new StringBuffer();
                while ((ch = isInputStream.read()) != -1)
                {
                    buffer.append((char) ch);
                }
                return buffer.toString();
            } else
            {
                return "false";
            }
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return "false";
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30555429/article/details/81981367