Java implementation of the sina weibo Oauth interface to send pictures and text methods

  • 2020-04-01 04:01:18
  • OfStack

This article illustrates the Java implementation of the sina weibo Oauth interface to send pictures and text methods. Share with you for your reference. The details are as follows:

Based on the Internet many people using the sina API to develop sina weibo users encounter the problem of unable to send pictures, many people stuck in this cloth. Present the code now, hope to help some friends.



public String uploadStatus(String token, String tokenSecret, File aFile, String status, String urlPath) {
  httpOAuthConsumer = new DefaultOAuthConsumer(consumerKey,consumerSecret);
  httpOAuthConsumer.setTokenWithSecret(token,tokenSecret);
  String result = null;
  try {
   URL url = new URL(urlPath);
   HttpURLConnection request = (HttpURLConnection) url.openConnection();
   request.setDoOutput(true);
   request.setRequestMethod("POST");
   HttpParameters para = new HttpParameters();
   para.put("status", URLEncoder.encode(status,"utf-8").replaceAll("\+", "%20"));
   String boundary = "---------------------------37531613912423";
   String content = "--"+boundary+"rnContent-Disposition: form-data; name="status"rnrn";
   String pic = "rn--"+boundary+"rnContent-Disposition: form-data; name="pic"; filename="image.jpg"rnContent-Type: image/jpegrnrn";
   byte[] end_data = ("rn--" + boundary + "--rn").getBytes();
   FileInputStream stream = new FileInputStream(aFile);
   byte[] file = new byte[(int) aFile.length()];
   stream.read(file);
   request.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); //Sets the form type and separator
   request.setRequestProperty("Content-Length", String.valueOf(content.getBytes().length + status.getBytes().length + pic.getBytes().length + aFile.length() + end_data.length)); //Set content length
   httpOAuthConsumer.setAdditionalParameters(para);
   httpOAuthConsumer.sign(request);
   OutputStream ot = request.getOutputStream();
   ot.write(content.getBytes());
   ot.write(status.getBytes());
   ot.write(pic.getBytes());
   ot.write(file);
   ot.write(end_data);
   ot.flush();
   ot.close();
   request.connect();
   if (200 == request.getResponseCode()) {
    result = "SUCCESS";
   }
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (OAuthMessageSignerException e) {
   e.printStackTrace();
  } catch (OAuthExpectationFailedException e) {
   e.printStackTrace();
  } catch (OAuthCommunicationException e) {
   e.printStackTrace();
  }
  return result;
}

I hope this article has been helpful to your Java programming.


Related articles: