Android http Post 传文件

    /**
     *
     * @param path url地址 例如:http://baidu.com
     * @param speech 上传的文件
     * @return
     */
    public static String doHttpClientPost(String path, File speech){
        try {
            HttpPost httpPost = new HttpPost(paramsEncoder(path));
            DefaultHttpClient client = new DefaultHttpClient();
            //使用BasicHttpEntity,将文件以FileInputStream的形式放在content中
            BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
            FileInputStream fileInputStream = new FileInputStream(speech);
            basicHttpEntity.setContent(fileInputStream);
            basicHttpEntity.setContentLength(speech.length());
            httpPost.setEntity(basicHttpEntity);

            HttpResponse response = client.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            if(code==200){
                //请求成功
                String result = EntityUtils.toString(response.getEntity());
                Log.e("httpResult",result);
                return result;
            }else{
                return null;
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    /***
     * url参数进行encoder ,根据自己的需要 也可不调用此方法
     * @param url
     * @return
     */
    private static String paramsEncoder(String url) {
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            try {
                URLEncoder.encode(str, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return url;
    }
}

你可能感兴趣的:(网络通信)