欢迎使用CSDN-markdown编辑器

代码块

代码块语法遵循标准markdown代码,例如:

public class UpLoadUtils {
 /*
 *上传文件
 *@param requestUrL 请求地址
 *@param filePath  上传文件地址
 */
    public static String doUploadFile(String requestUrl, String filePath)
            throws MalformedURLException, IOException {
        Log.e("-----", requestUrl + " file:" + filePath);
        String result = null;
        String end = "\r\n"; //换行符
        String twoHyphens = "--";//两个连字符
        String boundary = "******";//分界符,*号数目没具体定义
        try {
            URL url = new URL(requestUrl);
            //开始建立连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url
                    .openConnection();


          //设置请求Cookie,如何没有可以不请求
           httpURLConnection.setRequestProperty("Cookie", "CookieName");

            //设置连接超时
            httpURLConnection.setConnectTimeout(300 * 1000);
            httpURLConnection.setReadTimeout(300* 1000); // 缓存的最长时间
            //允许输入流
            httpURLConnection.setDoInput(true);
            //允许输出流
            httpURLConnection.setDoOutput(true);
            //Post请求方式,不能用缓存,设置为false
            httpURLConnection.setUseCaches(false);
            //设置请求方式为Post
            httpURLConnection.setRequestMethod("POST");
            //设置连接属性为Keep-Alive
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            //设置编码方式
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            //设置请求内容为表单数据
            httpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(
                    httpURLConnection.getOutputStream());
            //写入分割符  "--******"和换行符   
            dos.writeBytes(twoHyphens + boundary + end);
            //写入MIME类型 换行
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                    + encode(filePath.substring(filePath.lastIndexOf("/") + 1))
                    + "\""
                    + end);
            //写入换行
            dos.writeBytes(end);
            //打开文件输入流
            FileInputStream fis = new FileInputStream(filePath);
            //每次读入8k
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            //循环读入
            while ((count = fis.read(buffer)) != -1) {
                //写入dos输出流
                dos.write(buffer, 0, count);
            }
            //关闭文件输入流
            fis.close();
            //写入换行
            dos.writeBytes(end);
            //写入--******-- ,此行表示结束,然后换行
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            //输出缓存区
            dos.flush();
            dos.close();
            //Log.e("响应吗",httpURLConnection.getResponseCode()+"");
            //请求成功返回请求码200
            if (200 == httpURLConnection.getResponseCode()) {
               //打开conn的输入流
                InputStream is = httpURLConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                //获取返回结果
                result = br.readLine();
                //关闭输入流
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("----", "doUploadFile error:" + e.toString());
        }
        Log.e(TAG, "result=" + result);
        return result;
    }

    // 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
    private static String encode(String value) throws Exception {
        return URLEncoder.encode(value, "utf-8");
    }

    public static String postData(String postUrl, List<NameValuePair> params)
            throws Exception {
        String result = null;
        //建立连接
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //设置请求方式为Post
        HttpPost post = new HttpPost(postUrl);
        //传入请求参数实体
        post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
        //获取请求结果
        HttpResponse response = httpClient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        //返回200表示成功
        if (statusCode == 200) {
           //获取返回结果
            result = readString(response.getEntity());
        } else {
            throw new IllegalStateException("Status Line " + statusCode);
        }

        return result;
    }

    private static String readString(HttpEntity entity) throws Exception {
        StringBuffer buffer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                entity.getContent()));
        String temp = null;
        while ((temp = reader.readLine()) != null) {
            buffer.append(temp);
        }
        return buffer.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值