本以为新浪发布图片和发布文字一样的简单,但很悲剧。。。。。。。远不是想象的那样。
现在分享一下代码。
/** * 发表带图片的微博 * * @param token * @param tokenSecret * @param status * 发表的内容 * @param urlPath * 图片的地址 本函数没有用到,我直接在函数中创建的。 * @return */ public static void uploadStatus(String token, String tokenSecret, String imageUrl, String status) { File files = Environment.getExternalStorageDirectory(); String sdPath = files.getAbsolutePath(); // 请保证SD卡根目录下有这张图片文件 String urlPath = sdPath + "/" + "c.jpg"; File imageFile = new File(urlPath); if (!imageFile.exists()) { System.out.println("没有该图片"); } httpOauthConsumer = new DefaultOAuthConsumer("你的AppKey","你的AppSecret");//记得用你的替换一下 httpOauthConsumer.setTokenWithSecret(token, tokenSecret);//token tokenSecret之前工作的任务 try { URL url = new URL(Constants.XinLangUpload);//URL:http://api.t.sina.com.cn/statuses/upload.json HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); HttpParameters httpParameters = new HttpParameters(); httpParameters.put("status", URLEncoder.encode(status, "utf-8").replaceAll("\\+", "%20")); String boundary = "---------------------------37531613912423"; String content = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"status\"\r\n\r\n"; String pic = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"pic\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"; byte[] end_data = ("\r\n--" + boundary + "--\r\n").getBytes(); FileInputStream stream = new FileInputStream(imageFile); byte[] file = new byte[(int) imageFile.length()]; stream.read(file); request.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // 设置表单类型和分隔符 request.setRequestProperty( "Content-Length", String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + imageFile.length() + end_data.length)); // 设置内容长度 httpOauthConsumer.setAdditionalParameters(httpParameters); httpOauthConsumer.sign(request); OutputStream outputStream = request.getOutputStream(); outputStream.write(content.getBytes()); outputStream.write(status.getBytes()); outputStream.write(pic.getBytes()); outputStream.write(file); outputStream.write(end_data); outputStream.flush(); outputStream.close(); request.connect(); if (200 == request.getResponseCode()) { System.out.println("发布成功"); } else { System.out.println("异常code:" + request.getResponseCode()); } } catch (Exception e1) { e1.printStackTrace(); } }