private AccountInfo checkIn(AccountInfo acc) { // TODO Auto-generated method stub if (client == null) { acc.state = UNKNOWN_FAIL; return acc; } ArrayList<BasicNameValuePair> valueList = new ArrayList<BasicNameValuePair>(); try { UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valueList, "UTF-8"); HttpPost post = new HttpPost("http://www.xiami.com/task/signin"); post.setHeader("Referer", "http://www.xiami.com/"); post.setEntity(urlEncodedFormEntity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { acc = isCheck(acc); if (acc.day > 0) acc.state = SUCCESS; else acc.state = CHECK_FAIL; } else { acc.state = SERVER_FAIL; } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return acc; }
private void sendProposal( String capabilities2, String rate2, String email2, String subject2, String message2) { // Log.d("TAG",key); MyHttpClient client = new MyHttpClient(Proposal.this); HttpPost post = new HttpPost("https://helium.staffittome.com/apis/create_proposal"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("session_key", staffkey)); nameValuePairs.add(new BasicNameValuePair("capability_id", capabilities2)); nameValuePairs.add(new BasicNameValuePair("payment_method", "1")); nameValuePairs.add(new BasicNameValuePair("rate", rate2)); nameValuePairs.add(new BasicNameValuePair("email", email2)); nameValuePairs.add(new BasicNameValuePair("subject", subject2)); nameValuePairs.add(new BasicNameValuePair("message", message2)); try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = client.execute(post, responseHandler); Log.d("TAG", "TEST RESULTS FROM HTTPS SEND PROPOSAL IS: " + responseBody); Toast.makeText(getApplicationContext(), responseBody, 0).show(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
private String search() { String query = "sessionId=" + Sscion.getSsid() + "&" + "pageno=" + 1; HttpGet httpRequest = new HttpGet(URLs.ASK_URL + query); String strResult = " "; try { HttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { strResult = EntityUtils.toString(httpResponse.getEntity()); } result = JsonUtils.fjson2(strResult); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
public static Long getProjectIdByName(String projectName, RestClient restClient) { Long projectId = 0L; HttpResponse response = null; try { response = restClient .getHttpclient() .execute( new HttpGet( restClient.getUrl() + "/flex/services/rest/latest/project?name=" + URLEncoder.encode(projectName, "utf-8")), restClient.getContext()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { JSONArray projArray = new JSONArray(string); List<Long> projectIdList = new ArrayList<Long>(); for (int i = 0; i < projArray.length(); i++) { Long id = projArray.getJSONObject(i).getLong("id"); projectIdList.add(id); } Collections.sort(projectIdList); projectId = projectIdList.get(0); } catch (JSONException e) { e.printStackTrace(); } } else { try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return projectId; }
private AccountInfo loginIn(AccountInfo acc) { // TODO Auto-generated method stub if (client == null) { acc.state = UNKNOWN_FAIL; return acc; } ArrayList<BasicNameValuePair> valueList = new ArrayList<BasicNameValuePair>(); BasicNameValuePair value = null; value = new BasicNameValuePair("email", acc.name); valueList.add(value); value = new BasicNameValuePair("password", acc.pass); valueList.add(value); value = new BasicNameValuePair("LoginButton", "登录"); valueList.add(value); try { UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(valueList, "UTF-8"); HttpPost post = new HttpPost("http://www.xiami.com/web/login"); post.setHeader("Referer", "http://www.xiami.com/web/login"); post.setEntity(urlEncodedFormEntity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity(), "UTF-8"); if (res.contains("会员登录")) { if (res.contains("请输入验证码")) { acc.state = LOGIN_VALIDATE_FAIL; } else { acc.state = LOGIN_FAIL; } } else if (res.contains("快捷操作")) { acc = isCheck(acc); if (acc.day > 0) acc.state = IS_CHECKED; else acc.state = SUCCESS; } else { acc.state = SERVER_FAIL; } } else { acc.state = SERVER_FAIL; } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return acc; }
private boolean setHttpEntity(HttpPost httpPost, JSONObject postEntity) { try { httpPost.setEntity(new StringEntity(postEntity.toString())); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); Log.e(Global.TAG, "Application update http entity error"); return false; } catch (ParseException e) { e.printStackTrace(); Log.e(Global.TAG, "Application update http entity error"); return false; } return true; }
public JSONArray get(String url) { HttpGet request = new HttpGet(url); DefaultHttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); return new JSONArray(EntityUtils.toString(response.getEntity(), "UTF-8")); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return null; }
/** 发送 get请求 */ public void get() { CloseableHttpClient httpclient = HttpClients.createDefault(); try { // 创建httpget. HttpGet httpget = new HttpGet("http://www.baidu.com"); // httpget.addHeader("Content-Type","application/x-www-form-urlencoded; charset=GBK"); System.out.println("executing request " + httpget.getURI()); // 执行get请求. CloseableHttpResponse response = httpclient.execute(httpget); try { // 获取响应实体 HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); // 打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { // String responseString = new String(EntityUtils.toString(entity).getBytes("gbk")); // responseString = new String(responseBody.getBytes("ISO-8859-1"),"UTF-8"); // System.out.println(responseString); // 打印响应内容长度 System.out.println("Response content length: " + entity.getContentLength()); // 打印响应内容 System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { response.close(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } }
@Override public List<City> consume_response(Object data) { List<City> cities = null; if (data != null) { if (data instanceof HttpResponse) { // Expecting the json response try { // String jsonStr = EntityUtils.toString(((HttpResponse) data).getEntity()); JSONTokener jsonTokener = new JSONTokener(jsonStr); JSONArray jsonArray = new JSONArray(jsonTokener); cities = new ArrayList<City>(jsonArray.length()); int length = jsonArray.length(); for (int i = 0; i < length; i++) { JSONObject jsonCity = (JSONObject) jsonArray.get(i); City city = new City(); city.set_id(Integer.toString(jsonCity.getInt("_id"))); city.setName(jsonCity.getString("name")); city.setType(jsonCity.getString("type")); JSONObject jsonCityGeoPos = (JSONObject) jsonCity.get("geo_position"); city.setLongitutde(Double.toString(jsonCityGeoPos.getDouble("longitude"))); city.setLat(Double.toString(jsonCityGeoPos.getDouble("latitude"))); cities.add(city); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } return cities; }
private JSONObject getResponseAsJSON(HttpResponse response) { JSONObject responseJson; try { responseJson = new JSONObject(EntityUtils.toString(response.getEntity())); } catch (ParseException e) { e.printStackTrace(); Log.e(Global.TAG, "Application content downloader response to JSON error"); return null; } catch (JSONException e) { e.printStackTrace(); Log.e(Global.TAG, "Application content downloader response to JSON error"); return null; } catch (IOException e) { e.printStackTrace(); Log.e(Global.TAG, "Application content downloader response to JSON error"); return null; } return responseJson; }
public static String get(String url) { String body = null; try { // Get请求 HttpGet httpget = new HttpGet(url); System.out.println( "url:" + httpget.getURI().toString() + "?" + "func=013001&catName=S0NTeGiEvFO+eQdgmEL3j5a4KITbfTegqp2M9Ef4/Yc="); httpget.setURI( new URI( httpget.getURI().toString() + "?" + "func=013001&catName=S0NTeGiEvFO+eQdgmEL3j5a4KITbfTegqp2M9Ef4/Yc=")); // 设置头 // 发送请求 HttpResponse httpresponse = httpClient.execute(httpget); // 获取返回数据 HttpEntity entity = httpresponse.getEntity(); body = EntityUtils.toString(entity); } catch (ParseException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 httpClient.getConnectionManager().shutdown(); } return body; }
static void getTokenFromRefreshToken() { access_token = null; expires_in = -1; token_start_time = -1; if (gProps == null) { initGProps(); } /* Try refresh token */ // Query for token now that user has gone through browser part // of // flow // The method used in getTokensFromCode should work here as well - I // think URL encoded Form is the recommended way... HttpPost post = new HttpPost(gProps.token_uri); post.addHeader("accept", "application/json"); post.addHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4); nameValuePairs.add(new BasicNameValuePair("client_id", gProps.client_id)); nameValuePairs.add(new BasicNameValuePair("client_secret", gProps.client_secret)); nameValuePairs.add(new BasicNameValuePair("refresh_token", refresh_token)); nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token")); try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { try { response = httpclient.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseJSON = EntityUtils.toString(resEntity); ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON); access_token = root.get("access_token").asText(); // refresh_token = // root.get("refresh_token").asText(); token_start_time = System.currentTimeMillis() / 1000; expires_in = root.get("expires_in").asInt(); } } else { log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase()); HttpEntity resEntity = response.getEntity(); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { log.error("Error obtaining access token: " + e.getMessage()); } finally { if (response != null) { response.close(); } httpclient.close(); } } catch (IOException io) { log.error("Error closing connections: " + io.getMessage()); } }
static void getTokensFromCode() { access_token = null; expires_in = -1; token_start_time = -1; refresh_token = null; new File("/home/sead/refresh.txt").delete(); if (gProps == null) { initGProps(); } // Query for token now that user has gone through browser part // of // flow HttpPost tokenRequest = new HttpPost(gProps.token_uri); MultipartEntityBuilder tokenRequestParams = MultipartEntityBuilder.create(); tokenRequestParams.addTextBody("client_id", gProps.client_id); tokenRequestParams.addTextBody("client_secret", gProps.client_secret); tokenRequestParams.addTextBody("code", device_code); tokenRequestParams.addTextBody("grant_type", "http://oauth.net/grant_type/device/1.0"); HttpEntity reqEntity = tokenRequestParams.build(); tokenRequest.setEntity(reqEntity); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { response = httpclient.execute(tokenRequest); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { String responseJSON = EntityUtils.toString(resEntity); ObjectNode root = (ObjectNode) new ObjectMapper().readTree(responseJSON); access_token = root.get("access_token").asText(); refresh_token = root.get("refresh_token").asText(); token_start_time = System.currentTimeMillis() / 1000; expires_in = root.get("expires_in").asInt(); } } else { log.error("Error response from Google: " + response.getStatusLine().getReasonPhrase()); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (response != null) { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
/** HttpClient连接SSL */ public void ssl() { CloseableHttpClient httpclient = null; try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("d:\\tomcat.keystore")); try { // 加载keyStore d:\\tomcat.keystore trustStore.load(instream, "123456".toCharArray()); } catch (CertificateException e) { e.printStackTrace(); } finally { try { instream.close(); } catch (Exception ignore) { } } // 相信自己的CA和所有自签名的证书 SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); // 只允许使用TLSv1协议 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); // 创建http请求(get方式) HttpGet httpget = new HttpGet("https://localhost:8443/myDemo/Ajax/serivceJ.action"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); System.out.println(EntityUtils.toString(entity)); EntityUtils.consume(entity); } } finally { response.close(); } } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } finally { if (httpclient != null) { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public static Map<Long, String> getAllProjects(RestClient restClient) { Map<Long, String> projects = new TreeMap<Long, String>(); HttpResponse response = null; final String url = URL_GET_PROJECTS.replace("{SERVER}", restClient.getUrl()); try { response = restClient.getHttpclient().execute(new HttpGet(url), restClient.getContext()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (HttpHostConnectException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity entity = response.getEntity(); String string = null; try { string = EntityUtils.toString(entity); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { JSONObject projObject = new JSONObject(string); JSONArray projArray = projObject.getJSONArray("projects"); for (int i = 0; i < projArray.length(); i++) { JSONObject project = projArray.getJSONObject(i); Long id = project.getLong("id"); String projName = project.getString("name"); JSONArray issueTypes = project.getJSONArray("issuetypes"); boolean issueTypeTesstExists = false; for (int j = 0; j < issueTypes.length(); j++) { JSONObject issueType = issueTypes.getJSONObject(j); String issueTypeName = issueType.getString("name"); if (issueTypeName.trim().equalsIgnoreCase(TEST_ISSSUETYPE_NAME)) { issueTypeTesstExists = true; break; } } if (!issueTypeTesstExists) { continue; } projects.put(id, projName); } } catch (JSONException e) { e.printStackTrace(); } } else { projects.put(0L, "No Project"); try { throw new ClientProtocolException("Unexpected response status: " + statusCode); } catch (ClientProtocolException e) { e.printStackTrace(); } } return projects; }