HttpUrlConnection的POST方法怎么向一个带有参数的地址上传文件
HttpUrlConnection的POST方法如何向一个带有参数的地址上传文件?
我需要向一个类似于http://www.xxxxx.com?id=10001这样的网址上传一个文件
我也知道POST方法的话 参数要写在请求正文之中
只是不知道是在哪行代码中写入 求高手指导
------解决方案--------------------
HttpClient自带支持的,不需要你这么幸苦去搞。。。Google下大把实例代码:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost");
// 一个本地的文件
FileBody bin = new FileBody(new File("d:/BIMG1181.JPG"));
// 多部分的实体
MultipartEntity reqEntity = new MultipartEntity();
// 增加
reqEntity.addPart("bin", bin);
// 设置
httppost.setEntity(reqEntity);
System.out.println("执行: " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
我需要向一个类似于http://www.xxxxx.com?id=10001这样的网址上传一个文件
我也知道POST方法的话 参数要写在请求正文之中
只是不知道是在哪行代码中写入 求高手指导
- Java code
String urlPath = "http://www.xxxxx.com"; URL url = new URL(urlPath);// 得到网址 String BOUNDARY = "---------7d4a6d158c9";// 设置分隔线 byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线 HttpURLConnection conn = (HttpURLConnection) url.openConnection();//获得连接 // 参数设置 conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); OutputStream outputStream = conn.getOutputStream();//获得输出流 StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"file1\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); sb.append(end_data); byte[] data = sb.toString().getBytes(); outputStream.write(data); // 开始上传 int outSize; byte[] outBuff = new byte[1024]; while ((outSize = fileInputStream.read(outBuff, 0, 1024)) > 0) { outputStream.write(outBuff, 0, outSize);// 开始上传 } outputStream.flush(); outputStream.close(); fileInputStream.close();
------解决方案--------------------
HttpClient自带支持的,不需要你这么幸苦去搞。。。Google下大把实例代码:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost");
// 一个本地的文件
FileBody bin = new FileBody(new File("d:/BIMG1181.JPG"));
// 多部分的实体
MultipartEntity reqEntity = new MultipartEntity();
// 增加
reqEntity.addPart("bin", bin);
// 设置
httppost.setEntity(reqEntity);
System.out.println("执行: " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();