private CloudServersException parseCloudServersException(HttpResponse response) { CloudServersException cse = new CloudServersException(); try { BasicResponseHandler responseHandler = new BasicResponseHandler(); String body = responseHandler.handleResponse(response); CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser(); SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setContentHandler(parser); xmlReader.parse(new InputSource(new StringReader(body))); cse = parser.getException(); } catch (ClientProtocolException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (IOException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (ParserConfigurationException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (SAXException e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } catch (FactoryConfigurationError e) { cse = new CloudServersException(); cse.setMessage(e.getLocalizedMessage()); } return cse; }
@Override protected Boolean doInBackground(String... params) { Instrumentation.startTimer("UserLoginTask"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(GlobalDataProvider.getInstance().getRestServiceUrl() + "user/login"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username", params[0])); nameValuePairs.add(new BasicNameValuePair("password", params[1])); try { httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); Log.d(TAG, httppost.getRequestLine().getUri()); HttpResponse response = httpclient.execute(httppost); if (response != null && response.getEntity() != null) { String respStr = EntityUtils.toString(response.getEntity()); if (respStr != null && respStr.equalsIgnoreCase("Success")) { Header[] headers = response.getAllHeaders(); for (Header header : headers) { if ("set-cookie".equalsIgnoreCase(header.getName())) { String headerValue = header.getValue(); if (headerValue.startsWith(JSESSIONID)) { String jsessionId = headerValue.substring(0, headerValue.indexOf(';')); GlobalDataProvider.getInstance().setSessionId(jsessionId); } } } // TODO: Future enhancements - register the new account here?? success = true; Log.d("ADInstrumentation", "success"); return true; } else { error = true; } } else { exceptionOccured = true; exceptionMessage = "Unable to connect to server"; } } catch (UnsupportedEncodingException e1) { exceptionOccured = true; e1.getLocalizedMessage(); e1.printStackTrace(); } catch (ClientProtocolException e) { exceptionOccured = true; exceptionMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { exceptionOccured = true; exceptionMessage = e.getLocalizedMessage(); e.printStackTrace(); } finally { Instrumentation.stopTimer("UserLoginTask"); } Log.d("ADInstrumentation", "failure"); return false; }
/** * 发送微博 * * @param token * @param editText * @return */ public static Boolean sendWeibo(Oauth2AccessToken token, EditText editText, byte[] imgBuffer) { HttpPost postMethod; // 组织post参数:此处只实现最简单的发送消息,只填两个参数,其他见http://open.weibo.com/wiki/2/statuses/friends_timeline HttpClient httpClient = new DefaultHttpClient(); List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); String messageString = editText.getText().toString(); params.add(new BasicNameValuePair("status", messageString)); params.add(new BasicNameValuePair("access_token", token.getToken())); // 判断是否有图片,选择不同的接口 if (null != imgBuffer) { Log.w(TAG, "Image file include!"); params.add(new BasicNameValuePair("pic", imgBuffer.toString())); postMethod = new HttpPost(Contants.STATUESES_UPDATA_WITH_IMG_URL); } else { Log.w(TAG, "No images select!"); postMethod = new HttpPost(Contants.STATUESES_UPDATA_URL); } try { postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); HttpResponse httpResponse = httpClient.execute(postMethod); // 将返回结果转为字符串,通过文档可知返回结果为json字符串,结构请参考文档 String resultStr = EntityUtils.toString(httpResponse.getEntity()); Log.w(TAG, resultStr); // 从json字符串中建立JSONObject JSONObject resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { return false; } else { return true; } } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } return false; }
public static Object post(RequestModel model) { // Authenticator.setDefault(new Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication (Loggerin, password.toCharArray()); // } // }); DefaultHttpClient client = new DefaultHttpClient(); String url = model.host.concat(model.context.getString(model.requestUrl)); Logger.e("NetUtil里面的post的URL", url); HttpPost post = new HttpPost(url); post.setHeader( "Authorization", "Basic " + Base64.encodeToString((Loggerin + ":" + password).getBytes(), Base64.NO_WRAP)); HttpParams params = new BasicHttpParams(); params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 8000); HttpConnectionParams.setSoTimeout(params, 8000); post.setParams(params); Object obj = null; try { if (model.requestDataMap != null) { HashMap<String, String> map = model.requestDataMap; List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, String> entry : map.entrySet()) { BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()); pairList.add(pair); } HttpEntity entity = new UrlEncodedFormEntity(pairList, "UTF-8"); post.setEntity(entity); } HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String result = EntityUtils.toString(response.getEntity(), "UTF-8"); Logger.e(NetUtil.class.getSimpleName() + "1", result); try { obj = model.jsonParser.parseJSON(result); } catch (Exception e) { Log.e(NetUtil.class.getSimpleName() + "2", e.getLocalizedMessage(), e); } return obj; } } catch (ClientProtocolException e) { Log.e(NetUtil.class.getSimpleName() + "5", e.getLocalizedMessage(), e); } catch (IOException e) { Log.e(NetUtil.class.getSimpleName() + "6", e.getLocalizedMessage(), e); } return null; }
public static long getCurrentUserId(Oauth2AccessToken token) { JSONObject resultJson = null; HttpResponse httpResponse; HttpClient httpClient = new DefaultHttpClient(); // 传入get方法的请求地址和参数 HttpGet getMethod = new HttpGet(Contants.GET_CURRENT_USER_INFO_URL + "?" + "access_token=" + token.getToken()); try { // execute返回一个响应对象 httpResponse = httpClient.execute(getMethod); // 响应的内容对象 // 读取内容,用inputstream读取 String resultStr = EntityUtils.toString(httpResponse.getEntity()); resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { Log.w(TAG, "获取用户信息失败"); } // Log.i(TAG, resultJson.toString()); } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } try { return resultJson.getLong("uid"); } catch (JSONException e) { e.printStackTrace(); } return 0; }
/** * 使用psot方法发送http请求 * * @param context * @param params * @param baseUrl * @return */ public static JSONObject doPost( Context context, List<BasicNameValuePair> params, String baseUrl) { JSONObject resultJson = null; HttpClient httpClient = new DefaultHttpClient(); // 传入post方法的请求地址,即发送微博的api接口 HttpPost postMethod = new HttpPost(baseUrl); try { postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); HttpResponse httpResponse = httpClient.execute(postMethod); // 将返回结果转为字符串,通过文档可知返回结果为json字符串,结构请参考文档 String resultStr = EntityUtils.toString(httpResponse.getEntity()); Log.w(TAG, resultStr); // 从json字符串中建立JSONObject resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { Log.w(TAG, "post success"); } else { Log.w(TAG, "post fali"); } } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } return resultJson; }
/** * 获取所有新消息数,UID为当前登陆用户 * * @return */ public static NewMsg getNewMessageCounts(Oauth2AccessToken token, Long currentUID) { NewMsg newMsg = new NewMsg(); JSONObject resultJson = null; HttpResponse httpResponse; HttpClient httpClient = new DefaultHttpClient(); // 传入get方法的请求地址和参数 HttpGet getMethod = new HttpGet( Contants.GET_MESSAGE_COUNT_URL + "?" + "access_token=" + token.getToken() + "&true=" + currentUID); try { // execute返回一个响应对象 httpResponse = httpClient.execute(getMethod); // 响应的内容对象 // 读取内容,用inputstream读取 String resultStr = EntityUtils.toString(httpResponse.getEntity()); resultJson = new JSONObject(resultStr); // 如果发送微博失败的话,返回字段中有"error"字段,通过判断是否存在该字段即可知道是否发送成功 if (resultJson.has("error")) { Log.w(TAG, "获取用户信息失败"); } // Log.i(TAG, resultJson.toString()); } catch (UnsupportedEncodingException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ClientProtocolException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (ParseException e) { Log.w(TAG, e.getLocalizedMessage()); } catch (JSONException e) { Log.w(TAG, e.getLocalizedMessage()); } // 保存消息数 try { newMsg.setStatus(resultJson.getInt("status")); } catch (Exception e) { } try { newMsg.setFollower(resultJson.getInt("follower")); } catch (Exception e) { } try { newMsg.setCmt(resultJson.getInt("cmt")); } catch (Exception e) { } try { newMsg.setDm(resultJson.getInt("dm")); } catch (Exception e) { } try { newMsg.setMention(resultJson.getInt("mention_status") + resultJson.getInt("mention_cmt")); } catch (Exception e) { } return newMsg; }
@Override public void send(CrashReportData data) throws ReportSenderException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://oops.tomahawk-player.org/addreport.php"); StringBuilder body = new StringBuilder(); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add( new BasicNameValuePair("Version", data.getProperty(ReportField.APP_VERSION_NAME))); nameValuePairs.add(new BasicNameValuePair("BuildID", data.getProperty(ReportField.BUILD))); nameValuePairs.add(new BasicNameValuePair("ProductName", "tomahawk-android")); nameValuePairs.add(new BasicNameValuePair("Vendor", "Tomahawk")); nameValuePairs.add( new BasicNameValuePair("timestamp", data.getProperty(ReportField.USER_CRASH_DATE))); for (NameValuePair pair : nameValuePairs) { body.append("--thkboundary\r\n"); body.append("Content-Disposition: form-data; name=\""); body.append(pair.getName()).append("\"\r\n\r\n").append(pair.getValue()).append("\r\n"); } body.append("--thkboundary\r\n"); body.append("Content-Disposition: form-data; name=\"upload_file_minidump\"; filename=\"") .append(data.getProperty(ReportField.REPORT_ID)) .append("\"\r\n"); body.append("Content-Type: application/octet-stream\r\n\r\n"); body.append("============== Tomahawk Exception Report ==============\r\n\r\n"); body.append("Report ID: ").append(data.getProperty(ReportField.REPORT_ID)).append("\r\n"); body.append("App Start Date: ") .append(data.getProperty(ReportField.USER_APP_START_DATE)) .append("\r\n"); body.append("Crash Date: ") .append(data.getProperty(ReportField.USER_CRASH_DATE)) .append("\r\n\r\n"); body.append("--------- Phone Details ----------\r\n"); body.append("Phone Model: ").append(data.getProperty(ReportField.PHONE_MODEL)).append("\r\n"); body.append("Brand: ").append(data.getProperty(ReportField.BRAND)).append("\r\n"); body.append("Product: ").append(data.getProperty(ReportField.PRODUCT)).append("\r\n"); body.append("Display: ").append(data.getProperty(ReportField.DISPLAY)).append("\r\n"); body.append("-----------------------------------\r\n\r\n"); body.append("----------- Stack Trace -----------\r\n"); body.append(data.getProperty(ReportField.STACK_TRACE)).append("\r\n"); body.append("-----------------------------------\r\n\r\n"); body.append("------- Operating System ---------\r\n"); body.append("App Version Name: ") .append(data.getProperty(ReportField.APP_VERSION_NAME)) .append("\r\n"); body.append("Total Mem Size: ") .append(data.getProperty(ReportField.TOTAL_MEM_SIZE)) .append("\r\n"); body.append("Available Mem Size: ") .append(data.getProperty(ReportField.AVAILABLE_MEM_SIZE)) .append("\r\n"); body.append("Dumpsys Meminfo: ") .append(data.getProperty(ReportField.DUMPSYS_MEMINFO)) .append("\r\n"); body.append("-----------------------------------\r\n\r\n"); body.append("-------------- Misc ---------------\r\n"); body.append("Package Name: ").append(data.getProperty(ReportField.PACKAGE_NAME)).append("\r\n"); body.append("File Path: ").append(data.getProperty(ReportField.FILE_PATH)).append("\r\n"); body.append("Android Version: ") .append(data.getProperty(ReportField.ANDROID_VERSION)) .append("\r\n"); body.append("Build: ").append(data.getProperty(ReportField.BUILD)).append("\r\n"); body.append("Initial Configuration: ") .append(data.getProperty(ReportField.INITIAL_CONFIGURATION)) .append("\r\n"); body.append("Crash Configuration: ") .append(data.getProperty(ReportField.CRASH_CONFIGURATION)) .append("\r\n"); body.append("Settings Secure: ") .append(data.getProperty(ReportField.SETTINGS_SECURE)) .append("\r\n"); body.append("User Email: ").append(data.getProperty(ReportField.USER_EMAIL)).append("\r\n"); body.append("User Comment: ").append(data.getProperty(ReportField.USER_COMMENT)).append("\r\n"); body.append("-----------------------------------\r\n\r\n"); body.append("---------------- Logs -------------\r\n"); body.append("Logcat: ").append(data.getProperty(ReportField.LOGCAT)).append("\r\n\r\n"); body.append("Events Log: ").append(data.getProperty(ReportField.EVENTSLOG)).append("\r\n\r\n"); body.append("Radio Log: ").append(data.getProperty(ReportField.RADIOLOG)).append("\r\n"); body.append("-----------------------------------\r\n\r\n"); body.append("=======================================================\r\n\r\n"); body.append("--thkboundary\r\n"); body.append( "Content-Disposition: form-data; name=\"upload_file_tomahawklog\"; filename=\"Tomahawk.log\"\r\n"); body.append("Content-Type: text/plain\r\n\r\n"); body.append(data.getProperty(ReportField.LOGCAT)); body.append("\r\n--thkboundary--\r\n"); httppost.setHeader("Content-type", "multipart/form-data; boundary=thkboundary"); try { httppost.setEntity(new StringEntity(body.toString())); httpclient.execute(httppost); } catch (ClientProtocolException e) { Log.e(TAG, "send: " + e.getClass() + ": " + e.getLocalizedMessage()); } catch (IOException e) { Log.e(TAG, "send: " + e.getClass() + ": " + e.getLocalizedMessage()); } }