http发送图片,字节数组的方式

1.根据HttpURLConnection上传

public static JSONObject httpUploadImg(String postUrl,byte[] imgBuffer){
		URL url = new URL(postUrl);
		StringBuffer buffer = new StringBuffer();
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		String boundary = "--------httpUploadImg";
		Map<String , byte[]> byteparams = new HashMap<String, byte[]>();
		DataOutputStream ds;
		StringBuilder sb = new StringBuilder();
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setConnectTimeout(CONNECTION_TIMEOUT);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type", sb.append("multipart/form-data; boundary=").append(boundary).toString());
		byteparams.put("null.jpg", imgBuffer);
		try
        {
            conn.connect();
        }
        catch(SocketTimeoutException e)
        {
            throw new RuntimeException();
        }
		ds = new DataOutputStream(conn.getOutputStream());
		writeByteParams(ds, byteparams, boundary);
		paramsEnd(ds, boundary);
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();
		// 释放资源
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		JSONObject jsonObject = (JSONObject) JSONValue.parse(buffer.toString());
		return jsonObject;
	}

private static void writeByteParams(DataOutputStream ds, Map<String , byte[]> byteparams, String boundary) throws Exception{
		Set keySet = byteparams.keySet();
		for(Iterator it = keySet.iterator(); it.hasNext(); ds.writeBytes("\r\n")){
			String name = (String)it.next();
			byte[] value = (byte[])byteparams.get(name);
			ds.writeBytes((new StringBuilder()).append("--").append(boundary).append("\r\n").toString());
            ds.writeBytes((new StringBuilder()).append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(URLEncoder.encode(name, "UTF8")).append("\"\r\n").toString());
            //是jpg的格式
            ds.writeBytes((new StringBuilder()).append("Content-Type: img/jpg").append("\r\n").toString());
            ds.writeBytes("\r\n");
            ds.write(value);
		}
	}
	
	private static void paramsEnd(DataOutputStream ds, String boundary)throws Exception
    {
        ds.writeBytes((new StringBuilder()).append("--").append(boundary).append("--").append("\r\n").toString());
        ds.writeBytes("\r\n");
    }


2.httpClient发送图片

public static JSONObject httpUploadImg(String postUrl,byte[] imgBuffer){
		HttpPost httpPost = new HttpPost(postUrl);
		MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
		mpEntity.addBinaryBody("upfile", imgBuffer, ContentType.DEFAULT_BINARY, "null.jpg");
		httpPost.setEntity(mpEntity.build());
		// 创建默认的httpClient实例.    
        CloseableHttpClient httpclient = HttpClients.createDefault();  
		HttpResponse response;
		StringBuilder string = new StringBuilder();
		try {
			response = httpclient.execute(httpPost);
			HttpEntity resEntity = response.getEntity();
			BufferedReader in = new BufferedReader(new InputStreamReader(resEntity.getContent()));
		    String inputLine = null;
		    
			while((inputLine = in.readLine()) != null){
				string.append(inputLine);
				
			}
			in.close();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		JSONObject jsonObject = (JSONObject) JSONValue.parse(string.toString());
		return jsonObject;
	}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值