public Response multPartURL( String url, PostParameter[] params, ImageItem item, boolean authenticated) throws WeiboException { PostMethod post = new PostMethod(url); try { org.apache.commons.httpclient.HttpClient client = getHttpClient(); long t = System.currentTimeMillis(); Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } parts[parts.length - 1] = new ByteArrayPart(item.getContent(), item.getName(), item.getContentType()); } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); List<Header> headers = new ArrayList<Header>(); if (authenticated) { if (oauth == null) {} String authorization = null; if (null != oauth) { // use OAuth authorization = oauth.generateAuthorizationHeader("POST", url, params, oauthToken); } else { throw new IllegalStateException( "Neither user ID/password combination nor OAuth consumer key/secret combination supplied"); } headers.add(new Header("Authorization", authorization)); log("Authorization: " + authorization); } client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); client.executeMethod(post); Response response = new Response(); response.setResponseAsString(post.getResponseBodyAsString()); response.setStatusCode(post.getStatusCode()); log( "multPartURL URL:" + url + ", result:" + response + ", time:" + (System.currentTimeMillis() - t)); return response; } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } finally { post.releaseConnection(); } }
public Response httpRequest(HttpMethod method, Boolean WithTokenHeader, String token) throws WeiboException { InetAddress ipaddr; int responseCode = -1; try { ipaddr = InetAddress.getLocalHost(); List<Header> headers = new ArrayList<Header>(); if (WithTokenHeader) { if (token == null) { throw new IllegalStateException("Oauth2 token is not set!"); } headers.add(new Header("Authorization", "OAuth2 " + token)); headers.add(new Header("API-RemoteIP", ipaddr.getHostAddress())); client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); for (Header hd : headers) { log(hd.getName() + ": " + hd.getValue()); } } method .getParams() .setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); client.executeMethod(method); Header[] resHeader = method.getResponseHeaders(); responseCode = method.getStatusCode(); log("Response:"); log("https StatusCode:" + String.valueOf(responseCode)); for (Header header : resHeader) { log(header.getName() + ":" + header.getValue()); } Response response = new Response(); response.setResponseAsString(method.getResponseBodyAsString()); log(response.toString() + "\n"); if (responseCode != OK) { try { throw new WeiboException( getCause(responseCode), response.asJSONObject(), method.getStatusCode()); } catch (JSONException e) { e.printStackTrace(); } } return response; } catch (IOException ioe) { throw new WeiboException(ioe.getMessage(), ioe, responseCode); } finally { method.releaseConnection(); } }
@Test public void testOne() { String args[] = {}; init(args); resetToken(); refreshToken(); try { // Response res = weibo.getSearchUser("teisei", 10); Response res = weibo.getTopStatus("丰球集团", 10); System.out.println(res.toString()); } catch (Exception e) { // {"statuses":[{"created_at":"Sun May 13 18:38:30 +0800 // 2012","id":3445293779808422,"mid":"3445293779808422","idstr":"3445293779808422","text":"[\u7231\u4f60]\u6211\u5728\u8fd9\u91cc:#\u6d59\u6c5f\u4e30\u7403\u96c6\u56e2\u6709\u9650\u516c\u53f8#\u6b21\u996d\u996d\u2026\u6211\u997f\u4e86\uff0c\u997f\u4e86\u3002 http:\/\/t.cn\/zOEtprD","source_allowclick":0,"source_type":1,"source":"<a href=\"http:\/\/app.weibo.com\/t\/feed\/c66T5g\" rel=\"nofollow\">Android\u5ba2\u6237\u7aef<\/a>","favorited":false,"truncated":false,"in_reply_to_status_id":"","in_reply_to_user_id":"","in_reply_to_screen_name":"","pic_ids":["6e6bf15ejw1dswvmwun4fj"],"thumbnail_pic":"http:\/\/ww4.sinaimg.cn\/thumbnail\/6e6bf15ejw1dswvmwun4fj.jpg","bmiddle_pic":"http:\/\/ww4.sinaimg.cn\/bmiddle\/6e6bf15ejw1dswvmwun4fj.jpg","original_pic":"http:\/\/ww4.sinaimg.cn\/large\/6e6bf15ejw1dswvmwun4fj.jpg","geo":{"type":"Point","coordinates":[29.70396,120.2508]},"user":{"id":1852567902,"idstr":"1852567902","class":1,"screen_name":"\u971e\u971e\u971e\u5b9d\u8d1d","name":"\u971e\u971e\u971e\u5b9d\u8d1d","province":"33","city":"6","location":"\u6d59\u6c5f \u7ecd\u5174","description":"\u505a\u597d\u81ea\u5df1\uff0c\u522b\u7684\u4e8b\u60c5\u4e0a\u5929\u81ea\u6709\u5b89\u6392\uff5e","url":"http:\/\/625027974.qzone.qq.com","profile_image_url":"http:\/\/tp3.sinaimg.cn\/1852567902\/50\/5706180188\/0","cover_image_phone":"http:\/\/ww2.sinaimg.cn\/crop.0.0.640.640.640\/a1d3feabjw1ecassls6b2j20hs0hsq50.jpg","profile_url":"tutu3325749","domain":"tutu3325749","weihao":"","gender":"f","followers_count":602,"friends_count":313,"pagefriends_count":1,"statuses_count":448,"favourites_count":0,"created_at":"Thu Oct 14 01:19:34 +0800 2010","following":false,"allow_all_act_msg":false,"geo_enabled":true,"verified":false,"verified_type":-1,"ptype":0,"allow_all_comment":true,"avatar_large":"http:\/\/tp3.sinaimg.cn\/1852567902\/180\/5706180188\/0","avatar_hd":"http:\/\/ww4.sinaimg.cn\/crop.0.0.852.852.1024\/6e6bf15ejw8ekj66leszdj20no0npjuf.jpg","verified_reason":"","verified_trade":"","verified_reason_url":"","verified_source":"","verified_source_url":"","follow_me":false,"online_status":0,"bi_followers_count":149,"lang":"zh-cn","star":0,"mbtype":0,"mbrank":0,"block_word":0,"block_app":0,"ulevel":0,"badge_top":"","extend":{"privacy":{"mobile":1},"mbprivilege":"0000000000000000000000000000000000000000000000000000000000000000"},"credit_score":80,"urank":20},"annotations":[{"place":{"poiid":"B2094651DA6DA7F84393","title":"\u6d59\u6c5f\u4e30\u7403\u96c6\u56e2\u6709\u9650\u516c\u53f8","lon":120.2508,"lat":29.70396,"type":"checkin"}}],"reposts_count":0,"comments_count":6,"attitudes_count":0,"mlevel":0,"visible":{"type":0,"list_id":0},"url_objects":[{"url_ori":"http:\/\/t.cn\/zOEtprD","info":{"url_short":"http:\/\/t.cn\/zOEtprD","url_long":"http:\/\/m.weibo.cn\/poi?entry=client&poiid=B2094651DA6DA7F84393","type":0,"result":true,"title":"","description":"","last_modified":1336905510,"transcode":0},"like_count":0,"follower_count":0,"asso_like_count":0,"card_info_un_integrity":false},{"url_ori":"\u6d59\u6c5f\u4e30\u7403\u96c6\u56e2\u6709\u9650\u516c\u53f8","object_id":"1022:10080876aba069299deff3f921374debc962e0","like_count":0,"follower_count":0,"asso_like_count":0,"card_info_un_integrity":false}],"darwin_tags":[],"category":31}],"total_number":1} } }
public WeiboResponse(Response res) { try { mResponse = res; String limit = res.getResponseHeader("X-RateLimit-Limit"); if (null != limit) { rateLimitLimit = Integer.parseInt(limit); } String remaining = res.getResponseHeader("X-RateLimit-Remaining"); if (null != remaining) { rateLimitRemaining = Integer.parseInt(remaining); } String reset = res.getResponseHeader("X-RateLimit-Reset"); if (null != reset) { rateLimitReset = Long.parseLong(reset); } } catch (Exception e) { } }
public static List<User> constructUser(Response res) throws WeiboException { JSONObject json = res.asJSONObject(); JSONArray list = null; try { if (!json.isNull("users")) { list = json.getJSONArray("users"); } else { list = res.asJSONArray(); } int size = list.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(list.getJSONObject(i))); } return users; } catch (JSONException je) { throw new WeiboException(je); } }
public SchoolSearch(Response res) throws WeiboException { super(res); JSONObject json = res.asJSONObject(); try { id = json.getInt("id"); location = json.getString("location"); type = json.getLong("type"); schoolName = json.getString("school_name"); } catch (JSONException je) { throw new WeiboException(je.getMessage() + ":" + json.toString(), je); } }
public static String[] constructIds(Response res) throws WeiboException { try { JSONArray list = res.asJSONObject().getJSONArray("ids"); String temp = list.toString().substring(1, list.toString().length() - 2); String[] ids = temp.split(","); return ids; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
/** * @param res * @return * @throws WeiboException */ static List<User> constructResult(Response res) throws WeiboException { JSONArray list = res.asJSONArray(); try { int size = list.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(list.getJSONObject(i))); } return users; } catch (JSONException e) { } return null; }
public Emotion(Response res) throws WeiboException { super(res); JSONObject json = res.asJSONObject(); try { phrase = json.getString("phrase"); type = json.getString("type"); url = json.getString("url"); is_hot = json.getBoolean("is_hot"); order_number = json.getInt("order_number"); category = json.getString("category"); is_common = json.getBoolean("is_common"); } catch (JSONException je) { throw new WeiboException(je.getMessage() + ":" + json.toString(), je); } }
public static List<SchoolSearch> constructSchoolSearch(Response res) throws WeiboException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<SchoolSearch> schools = new ArrayList<SchoolSearch>(size); for (int i = 0; i < size; i++) { schools.add(new SchoolSearch(list.getJSONObject(i))); } return schools; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
static List<Count> constructCounts(Response res) throws WeiboException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<Count> counts = new ArrayList<Count>(size); for (int i = 0; i < size; i++) { counts.add(new Count(list.getJSONObject(i))); } return counts; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
public static List<FavoritesTag> constructTag(Response res) throws WeiboException { try { JSONArray list = res.asJSONObject().getJSONArray("tags"); int size = list.length(); List<FavoritesTag> tags = new ArrayList<FavoritesTag>(size); for (int i = 0; i < size; i++) { tags.add(new FavoritesTag(list.getJSONObject(i))); } return tags; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
public static List<User> constructUsers(Response res) throws WeiboException { try { JSONArray list = res.asJSONArray(); int size = list.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(list.getJSONObject(i))); } return users; } catch (JSONException jsone) { throw new WeiboException(jsone); } catch (WeiboException te) { throw te; } }
public static TagWapper constructTagWapper(Response res) { try { JSONArray tags = res.asJSONArray(); List<Tag> tagList = new ArrayList<Tag>(); for (int i = 0; i < tags.getJSONObject(0).getJSONArray("tags").length(); i++) { tagList.add(new Tag(tags.getJSONObject(0).getJSONArray("tags").getJSONObject(i))); } String id = tags.getJSONObject(0).getString("id"); return new TagWapper(tagList, id); } catch (JSONException e) { e.printStackTrace(); } catch (WeiboException e) { e.printStackTrace(); } return null; }
/** * @param res * @return * @throws WeiboException */ public static UserWapper constructWapperUsers(Response res) throws WeiboException { JSONObject jsonUsers = res.asJSONObject(); // asJSONArray(); try { JSONArray user = jsonUsers.getJSONArray("users"); int size = user.length(); List<User> users = new ArrayList<User>(size); for (int i = 0; i < size; i++) { users.add(new User(user.getJSONObject(i))); } long previousCursor = jsonUsers.getLong("previous_curosr"); long nextCursor = jsonUsers.getLong("next_cursor"); if (nextCursor == -1) { // 兼容不同标签名称 nextCursor = jsonUsers.getLong("nextCursor"); } return new UserWapper(users, previousCursor, nextCursor); } catch (JSONException jsone) { throw new WeiboException(jsone); } }
public MentionsIds(Response res) throws WeiboException { super(res); JSONObject json = res.asJSONObject(); try { nextCursor = json.getLong("next_cursor"); previousCursor = json.getLong("previous_cursor"); totalNumber = json.getLong("total_number"); hasvisible = json.getBoolean("hasvisible"); interval = json.getLong("interval"); JSONArray list = json.getJSONArray("statuses"); int size = list.length(); statusesIds = new ArrayList<String>(size); for (int i = 0; i < size; i++) { statusesIds.add(list.getString(i)); } } catch (JSONException jsone) { throw new WeiboException(jsone); } }
public static StatusWapper constructWapperStatus(Response res) throws WeiboException { JSONObject jsonStatus = res.asJSONObject(); // asJSONArray(); JSONArray statuses = null; try { if (!jsonStatus.isNull("statuses")) { statuses = jsonStatus.getJSONArray("statuses"); } if (!jsonStatus.isNull("reposts")) { statuses = jsonStatus.getJSONArray("reposts"); } int size = statuses.length(); List<Status> status = new ArrayList<Status>(size); for (int i = 0; i < size; i++) { status.add(new Status(statuses.getJSONObject(i))); } long previousCursor = jsonStatus.getLong("previous_curosr"); long nextCursor = jsonStatus.getLong("next_cursor"); long totalNumber = jsonStatus.getLong("total_number"); String hasvisible = jsonStatus.getString("hasvisible"); return new StatusWapper(status, previousCursor, nextCursor, totalNumber, hasvisible); } catch (JSONException jsone) { throw new WeiboException(jsone); } }
public Response httpRequest( String url, PostParameter[] postParams, boolean authenticated, String httpMethod) throws WeiboException { int retriedCount; int retry = retryCount + 1; Response res = null; for (retriedCount = 0; retriedCount < retry; retriedCount++) { int responseCode = -1; try { HttpURLConnection con = null; OutputStream osw = null; try { con = getConnection(url); con.setDoInput(true); setHeaders(url, postParams, con, authenticated, httpMethod); if (null != postParams || "POST".equals(httpMethod)) { con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setDoOutput(true); String postParam = ""; if (postParams != null) { postParam = encodeParameters(postParams); } log("Post Params: ", postParam); byte[] bytes = postParam.getBytes("UTF-8"); con.setRequestProperty("Content-Length", Integer.toString(bytes.length)); osw = con.getOutputStream(); osw.write(bytes); osw.flush(); osw.close(); } else if ("DELETE".equals(httpMethod)) { con.setRequestMethod("DELETE"); } else { con.setRequestMethod("GET"); } res = new Response(con); responseCode = con.getResponseCode(); if (DEBUG) { log("Response: "); Map<String, List<String>> responseHeaders = con.getHeaderFields(); for (String key : responseHeaders.keySet()) { List<String> values = responseHeaders.get(key); for (String value : values) { if (null != key) { log(key + ": " + value); } else { log(value); } } } } if (responseCode != OK) { if (responseCode < INTERNAL_SERVER_ERROR || retriedCount == retryCount) { throw new WeiboException( getCause(responseCode) + "\n" + res.asString(), responseCode); } // will retry if the status code is INTERNAL_SERVER_ERROR } else { break; } } finally { try { osw.close(); } catch (Exception ignore) { } } } catch (IOException ioe) { // connection timeout or read timeout if (retriedCount == retryCount) { throw new WeiboException(ioe.getMessage(), ioe, responseCode); } } try { if (DEBUG && null != res) { res.asString(); } log("Sleeping " + retryIntervalMillis + " millisecs for next retry."); Thread.sleep(retryIntervalMillis); } catch (InterruptedException ignore) { // nothing to do } } return res; }
/* */ StatusStream(Response response) throws IOException { /* 53 */ this(response.asStream()); /* 54 */ this.response = response; /* */ }
public Status(Response res) throws WeiboException { super(res); JSONObject json = res.asJSONObject(); constructJson(json); }