/** * Adds a set of cookies to the HTTPClient. Pass in a HashMap of <String, Object> to add the * cookie values to the client. These cookies persist until removed. * * @param cookies a HashMap of cookies * @param url the domain URL of the cookie */ public void setCookies(HashMap<String, String> cookies, String url) { if (cookies == null) { return; } // Set cookies client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); // Create cookie store BasicCookieStore store = (BasicCookieStore) (client.getCookieStore() == null ? new BasicCookieStore() : client.getCookieStore()); // Add cookies to request for (Map.Entry<String, String> entry : cookies.entrySet()) { BasicClientCookie cookie = new BasicClientCookie(entry.getKey(), entry.getValue()); if (url != null) { cookie.setDomain(url); } cookie.setPath("/"); store.addCookie(cookie); } // Add the cookie client.setCookieStore(store); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.data_layout); d_pb_ll = (LinearLayout) findViewById(R.id.data_progressbar_ll); dataUsedText = (TextView) findViewById(R.id.dataUsedText); mProgress = (ProgressBar) findViewById(R.id.percentDataUsed); dell = (LinearLayout) findViewById(R.id.data_error); detv = (TextView) findViewById(R.id.tv_failure); deb = (Button) findViewById(R.id.button_send_data); actionbar = getSupportActionBar(); actionbar.setTitle("Data Usage"); actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); actionbar.setHomeButtonEnabled(true); actionbar.setDisplayHomeAsUpEnabled(true); graph = (XYPlot) findViewById(R.id.mySimpleXYPlot); graph.setOnTouchListener(this); graph.setMarkupEnabled(false); labels = new Long[288]; downdata = new Float[288]; totaldata = new Float[288]; httpclient = ConnectionHelper.getThreadSafeClient(); httpclient.getCookieStore().clear(); BasicClientCookie cookie = new BasicClientCookie("AUTHCOOKIE", ConnectionHelper.getPNAAuthCookie(this, httpclient)); cookie.setDomain(".pna.utexas.edu"); httpclient.getCookieStore().addCookie(cookie); new fetchDataTask(httpclient).execute(); new fetchProgressTask(httpclient).execute(); }
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpPost httpost = new HttpPost( "https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&" + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("IDToken1", "username")); nvps.add(new BasicNameValuePair("IDToken2", "password")); httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); EntityUtils.consume(entity); System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
public static void main(String[] args) throws Exception { WebClient webClient = new WebClient(); String homepage = "http://mail.google.com/"; webClient.setURL(homepage, new URL(homepage)); HttpHost httpHost = webClient.createHttpHost(homepage); HttpGet httpGet = webClient.createGetMethod(homepage, "http://www.google.com"); HttpResponse response = webClient.execute(httpHost, httpGet); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) entity.consumeContent(); System.out.println("Initial set of cookies:"); DefaultHttpClient httpClient = (DefaultHttpClient) webClient.getHttpClient(); List<Cookie> cookies = httpClient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } HttpMethodHandler handler = new HttpMethodHandler(webClient); HttpSessionUtils httpSession = new HttpSessionUtils(handler, "ERROR"); StringBuilder builder = new StringBuilder( "https://www.google.com/accounts/ServiceLogin?service=mail&passive=true&rm=false&continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fui%3Dhtml%26zy%3Dl&bsv=1k96igf4806cy<mpl=default<mplcache=2"); builder.append('\n').append("username:password"); httpSession.login(builder.toString(), "utf-8", new URL(homepage), homepage); httpGet = webClient.createGetMethod("http://mail.google.com/mail/", "http://gmail.com"); response = webClient.execute(httpHost, httpGet); entity = response.getEntity(); HttpMethodHandler httpResponseReader = new HttpMethodHandler(webClient); byte[] bytes = httpResponseReader.readBody(response); org.vietspider.common.io.RWData.getInstance().save(new File("google_mail.html"), bytes); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) entity.consumeContent(); System.out.println("Post logon cookies:"); cookies = httpClient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } }
private void initializeCookies(DefaultHttpClient httpClient) { BasicClientCookie cookie = new BasicClientCookie("DAISForwardCookie_Check", "NO"); cookie.setDomain(DOMAIN); cookie.setPath("/"); cookie.setSecure(true); httpClient.getCookieStore().addCookie(cookie); }
private RailyatriCookies getRailyatriCookies() { String railyatriUrl = TRAIN_ENQUIRY_SERVER; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(railyatriUrl); RailyatriCookies railyatriCookies = null; try { HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { railyatriCookies = new RailyatriCookies(); railyatriCookies.setCookieSpecRegistry(httpClient.getCookieSpecs()); railyatriCookies.setCookieStore(httpClient.getCookieStore()); // For debugging only List<Cookie> cookies = railyatriCookies.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("No Cookies!!!"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("-" + cookies.get(i).toString()); } } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return railyatriCookies; }
/** * This method queries Google Reader for the list of subscribed feeds. * * @param sid authentication code to pass along in a cookie. * @return arr returns a JSONArray of JSONObjects for each feed. * <p>The JSONObject returned by the service looks like this: id: this is the feed url. title: * this is the title of the feed. sortid: this has not been figured out yet. firstitemsec: * this has not been figured out yet. */ public static JSONArray getSubscriptionList(String sid) { final DefaultHttpClient client = new DefaultHttpClient(); final HttpGet get = new HttpGet(SUB_URL + "/list?output=json"); final BasicClientCookie cookie = Authentication.buildCookie(sid); try { client.getCookieStore().addCookie(cookie); final HttpResponse response = client.execute(get); final HttpEntity respEntity = response.getEntity(); Log.d(TAG, "Response from server: " + response.getStatusLine()); final InputStream in = respEntity.getContent(); final BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = ""; String arr = ""; while ((line = reader.readLine()) != null) { arr += line; } final JSONObject obj = new JSONObject(arr); final JSONArray array = obj.getJSONArray("subscriptions"); reader.close(); client.getConnectionManager().shutdown(); return array; } catch (final Exception e) { Log.d(TAG, "Exception caught:: " + e.toString()); return null; } }
private Response doRequest(final Request<?> request, final HttpRequestBase fetcher) { if (fetcher == null) { return null; } List<Parameter> headers = request.getHeaders(); if (checkListOfParams(headers)) { for (Parameter parameter : headers) { Header header = new BasicHeader(parameter.getName(), parameter.getValue()); fetcher.addHeader(header); } } final DefaultHttpClient httpClient = getHttpClient(); List<Parameter> cookies = request.getCookies(); if (checkListOfParams(cookies)) { CookieStore cookieStore = httpClient.getCookieStore(); for (Parameter cookie : cookies) { cookieStore.addCookie(new BasicClientCookie(cookie.getName(), cookie.getValue())); } httpClient.setCookieStore(cookieStore); } return doRequest(fetcher, httpClient); }
/** Save the current cookie for future use */ public void saveCurrentCookies() { CookieStore cookieStore = mHttpClient.getCookieStore(); // Create local HTTP context localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); }
public boolean hasCookies() { CookieStore cookies = client.getCookieStore(); if (cookies != null) { return !cookies.getCookies().isEmpty(); } return false; }
public List<StepLog> getStepLog(Long stepCount, String feedURL) throws IOException { // Get steps details HttpGet httpGet = new HttpGet(feedURL + "?pageSize=" + stepCount); // hack !!! // Handle CSRF tokens cookies client.setCookieStore(handleCsrfCookies(client.getCookieStore())); // Authenticate if (OOBuildStep.getEncodedCredentials() != null) { httpGet.addHeader( "Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials())); } // Execute the request HttpResponse response = client.execute(httpGet); // Verify the response is OK Assert.isTrue( response.getStatusLine().getStatusCode() == 200, "Invalid response code [" + response.getStatusLine().getStatusCode() + "]"); String responseBody = EntityUtils.toString(response.getEntity()); List<StepLog> stepLog = gson.fromJson(responseBody, new TypeToken<List<StepLog>>() {}.getType()); // List<StepLog> stackTrace = createStackTrace(stepLog, "0"); // listener.annotate(new SimpleHtmlNote(stackTraceAsString(stackTrace))); // setJSONExecutionResult(responseBody); // responseBody = formatResult(responseBody); return stepLog; // return ""; }
// Obté cookie a partir d'un nom del client http especificat private Cookie getCookie(DefaultHttpClient cl, String name) { List<Cookie> cookies = cl.getCookieStore().getCookies(); for (int i = 0; i < cookies.size(); i++) { Cookie c = cookies.get(i); if (c.getName().equals(name)) return c; } return null; }
public void storeCookies(File file) { try { FileOutputStream fos = new FileOutputStream(file); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(httpClient.getCookieStore()); } catch (Exception e) { e.printStackTrace(); } }
@Override public void retrieve() throws RetrieverException { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient .getParams() .setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpContext context = new BasicHttpContext(); accounts = new HashMap<String, Account>(); try { CookieStore cookieStore = httpClient.getCookieStore(); BasicClientCookie newCookie = new BasicClientCookie("XPRDMBP1E", registrationCookie); newCookie.setVersion(0); newCookie.setDomain("bankservices.rabobank.nl"); newCookie.setPath("/"); cookieStore.addCookie(newCookie); if (!checkAppStatus(httpClient, context)) { throw new RetrieverException("Application status is not OK"); } if (!loginWithAccessCode(httpClient, context, accountNumber, accessCode)) { throw new RetrieverException("Login with access code failed", true); } List<Account> accountList = retrieveAccounts(httpClient, context); logoff(httpClient, context); accounts = new HashMap<String, Account>(); for (Account account : accountList) { accounts.put(account.getAccountName(), account); } for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if ("XPRDMBP1E".equals(cookie.getName())) { registrationCookie = cookie.getValue(); } } } catch (IOException e) { throw new RetrieverException(e); } }
private boolean isPurlRunning() throws URISyntaxException, HttpException, ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); URI url = new URI( "http://localhost:" + testInfo.getPurlzPort() + IdentifiersTestInfo.PURLZ_REST_LOGIN); HttpPost method = new HttpPost(url); List<NameValuePair> loginParams = new ArrayList<NameValuePair>(); loginParams.add(new BasicNameValuePair("id", IdentifiersTestInfo.PURLZ_USER)); loginParams.add(new BasicNameValuePair("passwd", IdentifiersTestInfo.PURLZ_PASSWORD)); loginParams.add(new BasicNameValuePair("referrer", "/docs/index.html")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(loginParams, "UTF-8"); method.setEntity(entity); try { System.out.println("isPurlRunning connecting to " + url); HttpResponse response = client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("PURL Login: HTTP Status code: " + statusCode); if (statusCode != HttpStatus.SC_OK) { throw new HttpException( " [" + statusCode + ":" + response.getStatusLine().toString() + "]"); } String responseStr = IdentifiersTestInfo.getResponseString(response); if (!responseStr.contains(IdentifiersTestInfo.PURLZ_WELCOME_MSG)) { System.out.println("BAD RESPONSE FROM SERVER [" + responseStr + "]"); return false; } System.out.println("Login to PURL successful..."); CookieStore store = client.getCookieStore(); for (Cookie cookie : store.getCookies()) { if (cookie.getName().equalsIgnoreCase(IdentifiersTestInfo.PURLZ_LOGIN_COOKIE)) { testInfo.setPurlzLoginCookie(cookie); return true; } } } finally { // Release the connection. method.abort(); client.getConnectionManager().shutdown(); } return false; }
/** Create clone of existing RLHttpClient object */ @Override public RLHttpClient clone() { RLHttpClient brother = new RLHttpClient(mConnectionTimeout, mSocketTimeout); if (mHttpClient != null) { CookieStore cookieStore = mHttpClient.getCookieStore(); DefaultHttpClient cloneHttpClient = (DefaultHttpClient) brother.getHttpClient(); cloneHttpClient.setCookieStore(cookieStore); } return brother; }
public NoahHi(String username, String password) throws IOException { this.username = username; this.password = password; HttpClientFactory httpClientFactory = new HttpClientFactory(); httpClient = httpClientFactory.generateClient(username, password); login(); welcome(); init(); messageHttpClient = new DefaultHttpClient(); messageHttpClient.setCookieStore(httpClient.getCookieStore()); // pick(); }
public void signUp(View view) { EditText email = (EditText) findViewById(R.id.email); EditText pw = (EditText) findViewById(R.id.password); EditText nameField = (EditText) findViewById(R.id.name); String username = email.getText().toString(); String password = pw.getText().toString(); String name = nameField.getText().toString(); try { URI uri = new URI("http://severe-leaf-6733.herokuapp.com/users"); DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(uri); JSONObject json = new JSONObject(); JSONObject m = new JSONObject(); m.put("name", name); m.put("email", username); m.put("password", password); json.put("user", m); StringEntity se = new StringEntity(json.toString()); post.setEntity(se); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); BasicResponseHandler responseHandler = new BasicResponseHandler(); String responseString = client.execute(post, responseHandler); GsonBuilder g = new GsonBuilder(); g.setDateFormat("E MMM d HH:mm:ss Z y"); Gson gson = g.create(); User um = gson.fromJson(responseString, User.class); if (um.getID() != 0) { CookieStore cookieStore = client.getCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); Global.localContext = localContext; Global.client = client; Global.user_id = um.getID(); Intent myIntent = new Intent(getApplicationContext(), Root.class); startActivity(myIntent); } else { Toast.makeText(this, "Unable to Sign Up", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Log.e("Sign Up Error", e.getMessage()); } }
public void addCookie(String key, String val, String host, String path) { Cookie c = new Cookie(key, val, host, path); // 设置Cookie String name = c.name(); String value = c.value(); List<String> vals = this.cookies.get(name); if (vals == null) vals = new ArrayList<String>(); vals.add(value); this.cookies.put(key, vals); BasicClientCookie clientCookie = new BasicClientCookie(name, value); clientCookie.setPath(c.path()); clientCookie.setDomain(c.domain()); httpClient.getCookieStore().addCookie(clientCookie); }
private void saveCookiesToPreferences(Context context, DefaultHttpClient client) { final SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME_SUMC_COOKIES, Context.MODE_PRIVATE); final Editor edit = sharedPreferences.edit(); edit.clear(); int i = 0; for (Cookie cookie : client.getCookieStore().getCookies()) { edit.putString(PREFERENCES_COOKIE_NAME + i, cookie.getName()); edit.putString(PREFERENCES_COOKIE_VALUE + i, cookie.getValue()); edit.putString(PREFERENCES_COOKIE_DOMAIN + i, cookie.getDomain()); edit.putString(PREFERENCES_COOKIE_PATH + i, cookie.getPath()); i++; } edit.commit(); }
public void handleMessage(android.os.Message msg) { DefaultHttpClient httpClient; httpClient = (DefaultHttpClient) httpRequest.getHttpClient(); CookieStore mCookieStore = httpClient.getCookieStore(); List<Cookie> cookies = mCookieStore.getCookies(); String PHPSESSID = null; for (int i = 0; i < cookies.size(); i++) { // 这里是读取Cookie['PHPSESSID']的值存在静态变量中,保证每次都是同一个值 if ("PHPSESSID".equals(cookies.get(i).getName())) { PHPSESSID = cookies.get(i).getValue(); userShare.SaveSession(PHPSESSID); Log.e("PHPSESSID", PHPSESSID + ""); break; } } };
private void loadCookiesFromPreferences(Context context, DefaultHttpClient client) { final CookieStore cookieStore = client.getCookieStore(); final SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME_SUMC_COOKIES, Context.MODE_PRIVATE); int i = 0; while (sharedPreferences.contains(PREFERENCES_COOKIE_NAME + i)) { final String name = sharedPreferences.getString(PREFERENCES_COOKIE_NAME + i, null); final String value = sharedPreferences.getString(PREFERENCES_COOKIE_VALUE + i, null); final BasicClientCookie result = new BasicClientCookie(name, value); result.setDomain(sharedPreferences.getString(PREFERENCES_COOKIE_DOMAIN + i, null)); result.setPath(sharedPreferences.getString(PREFERENCES_COOKIE_PATH + i, null)); cookieStore.addCookie(result); i++; } }
/** * @author Owater * @createtime 2015-1-14 上午12:23:06 @Decription 登录和再次登录 * @param params * @param url * @return */ public static String login( Context context, List<NameValuePair> params, String url, String jdycode) { String result = ""; if (!isNetworkConnected(context)) { return Constants.NOT_NET + ""; } try { HttpPost httpRequest = new HttpPost(url); if (params != null) { HttpEntity httpEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8); httpRequest.setEntity(httpEntity); } DefaultHttpClient httpClient = getHttpClient(); httpClient.getParams().setParameter("http.socket.timeout", new Integer(30000)); if (JSESSIONID != null && jdycode != null) { httpRequest.setHeader("Cookie", "JSESSIONID=" + JSESSIONID); } HttpResponse httpResponse = httpClient.execute(httpRequest); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { result = EntityUtils.toString(httpResponse.getEntity()); CookieStore mCookieStore = httpClient.getCookieStore(); List<Cookie> cookies = mCookieStore.getCookies(); // 读取服务器返回的cookie for (int i = 0; i < cookies.size(); i++) { String cookieName = cookies.get(i).getName(); if ("JSESSIONID".equals(cookieName)) { JSESSIONID = cookies.get(i).getValue(); break; } } Log.i("commit", "提交成功"); } else { result = Constants.GETFALL + ""; Log.i("commit", "提交失败"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
@Override public void onLetterSend(int id, String guid) { if (id > 1) { AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("Send successful"); alertDialog.setMessage("Your letter was sent."); alertDialog.setButton( "Yay", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // here you can add functions } }); alertDialog.show(); httpClient = new DefaultHttpClient(); List<Cookie> cookies = httpClient.getCookieStore().getCookies(); for (int i = 0; i < cookies.size(); i++) { cookie = cookies.get(i); } // ------- Web Browser activity CookieSyncManager.createInstance(this); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setCookie( "www.letterstocrushes.com", guid + "=1; domain=www.letterstocrushes.com"); CookieSyncManager.getInstance().sync(); mAdapter = new MyAdapter(getSupportFragmentManager(), "letter/" + Integer.toString(id), ""); mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); mPager.setCurrentItem(1); } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); courseID = getArguments().getString("courseID"); courseName = getArguments().getString("courseName"); viewUri = getArguments().getString("viewUri"); itemName = getArguments().getString("itemName"); setHasOptionsMenu(true); attachments = new ArrayList<bbFile>(); attachmentAdapter = new dlableItemAdapter(getSherlockActivity(), attachments); content = ""; client = ConnectionHelper.getThreadSafeClient(); BasicClientCookie cookie = new BasicClientCookie( "s_session_id", ConnectionHelper.getBBAuthCookie(getSherlockActivity(), client)); cookie.setDomain("courses.utexas.edu"); client.getCookieStore().addCookie(cookie); }
/** * 获取标准 Cookie ,并存储 * * @param httpClient */ private void getCookie(DefaultHttpClient httpClient) { List<Cookie> cookies = httpClient.getCookieStore().getCookies(); // StringBuffer sb = new StringBuffer(); for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); if (!TextUtils.isEmpty(cookieName) && !TextUtils.isEmpty(cookieValue)) { if ("JSESSIONID".equalsIgnoreCase(cookieName)) { JSESSIONIDStr = cookieValue; } } } // Log. e( "cookie", sb.toString()); if (JSESSIONIDStr != null && !"".equals(JSESSIONIDStr)) { appContext .getSharedPreferences(BaseActivity.SETTING_INFOS, 0) .edit() .putString(BaseActivity.COOKIES_STR, JSESSIONIDStr) .commit(); } }
private Response doRequest(final HttpRequestBase request, final DefaultHttpClient httpClient) { final Response response = new Response(); int resultCode; try { HttpResponse httpResponse = httpClient.execute(request); InputStream stream = httpResponse.getEntity().getContent(); response.setStreamString(RequestUtils.convertStreamToString(stream)); Header[] headers = httpResponse.getAllHeaders(); if (headers != null && headers.length != 0) { for (Header header : headers) { response.setHeader(header.getName(), header.getValue()); } } List<Cookie> cookies = httpClient.getCookieStore().getCookies(); if (cookies != null && !cookies.isEmpty()) { for (Cookie cookie : cookies) { response.setCookies(cookie.getName(), cookie.getValue()); } } resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode == 200 || resultCode == 302) { response.setStatus(ResponseStatus.SUCCESS); } else { response.setStatus(ResponseStatus.FAILED); } response.setResultCode(resultCode); return response; } catch (final Exception ex) { // TO DO: create types of response statuses for all kind of exceptions return buildErrorResponse(ex.getMessage(), ResponseStatus.FAILED); } }
private String login(int... ids) { Log.d(TAG, "login(ids... method start"); String result = ""; String result2 = ""; ArrayList<RecipeGeneral> recipes = null; try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(Constants.URL_LOGIN); httpget.setHeader("Accept", "application/json"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); Log.d(TAG, "Login form get: " + response.getStatusLine()); Log.d(TAG, "Entity: " + entity.toString()); if (entity != null) { result = HttpFactory.convertStreamToString(entity.getContent()); Log.d(TAG, "Result: " + result); } List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { Log.d(TAG, "No cookies"); } else { for (int i = 0; i < cookies.size(); i++) { Log.d(TAG, "Cookies: " + cookies.get(i).toString()); } } JSONObject jsonResponse = new JSONObject(result.trim()); Log.d(TAG, "jsonResponce: " + jsonResponse.toString()); String token_value = jsonResponse.getString("token_value"); String token_name = jsonResponse.getString("token_name"); Log.d(TAG, "token_value: " + token_value); Log.d(TAG, "token_name: " + token_name); HttpPost httpost = new HttpPost(Constants.URL_LOGIN); httpost.setHeader("Accept", "application/json"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("user[email]", login)); nvps.add(new BasicNameValuePair("user[password]", password)); nvps.add(new BasicNameValuePair(token_name, token_value)); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response1 = httpclient.execute(httpost); HttpEntity entity1 = response1.getEntity(); Log.d(TAG, "Login form post: " + response1.getStatusLine()); if (entity1 != null) { result = HttpFactory.convertStreamToString(entity1.getContent()); Log.d(TAG, "Entity: " + result); } StringBuilder idsParams = new StringBuilder(); for (int id : ids) { idsParams.append("&ids[]=" + id); } HttpGet httpget2 = new HttpGet(Constants.URL_SYNC + "?ids[]=0" + idsParams); httpget2.setHeader("Accept", "application/json"); Log.d(TAG, "Request line: " + httpget2.getRequestLine()); Log.d(TAG, "Request params: " + httpget2.getParams()); Log.d(TAG, "Request uri: " + httpget2.getURI()); HttpResponse response2 = httpclient.execute(httpget2); HttpEntity entity2 = response2.getEntity(); Log.d(TAG, "Login form get2: " + response2.getStatusLine()); Log.d(TAG, "Entity2: " + entity2.toString()); if (entity2 != null) { result2 = HttpFactory.convertStreamToString(entity2.getContent()); Log.d(TAG, "Result2: " + result2); } List<Cookie> cookies2 = httpclient.getCookieStore().getCookies(); if (cookies2.isEmpty()) { Log.d(TAG, "No cookies2 "); } else { for (int i = 0; i < cookies2.size(); i++) { Log.d(TAG, "Cookies2 : " + cookies2.get(i).toString()); } } } catch (Exception e) { e.printStackTrace(); receiver.send(Constants.AUTHORIZATION_NOT_PASSED, null); } return result2; }
/** * Makes HTTP call with FORM authentication. * * @param URL * @param user * @param pass * @param expectedStatusCode * @throws Exception */ public static void makeCall(String URL, String user, String pass, int expectedStatusCode) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpGet httpget = new HttpGet(URL); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); // We should get the Login Page StatusLine statusLine = response.getStatusLine(); System.out.println("Login form get: " + statusLine); assertEquals(200, statusLine.getStatusCode()); System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // We should now login with the user name and password HttpPost httpost = new HttpPost(URL + "/j_security_check"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("j_username", user)); nvps.add(new BasicNameValuePair("j_password", pass)); httpost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); response = httpclient.execute(httpost); entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); statusLine = response.getStatusLine(); // Post authentication - we have a 302 assertEquals(302, statusLine.getStatusCode()); Header locationHeader = response.getFirstHeader("Location"); String location = locationHeader.getValue(); HttpGet httpGet = new HttpGet(location); response = httpclient.execute(httpGet); entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // Either the authentication passed or failed based on the expected status code statusLine = response.getStatusLine(); assertEquals(expectedStatusCode, statusLine.getStatusCode()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
public static void main(String args[]) throws ClientProtocolException, IOException { logger.info("start1"); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://202.102.41.71/portal/login!login.action"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("GET RESPONSE STATUS: " + response.getStatusLine()); if (entity != null) { System.out.println("RESPONSE BODY: " + EntityUtils.toString(entity)); EntityUtils.consume(entity); } System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } System.out.println("=============================================="); // 地址 HttpPost httpost = new HttpPost("http://202.102.41.71/portal/login!login.action"); // 设置头 Header[] headers = new Header[1]; headers[0] = new BasicHeader( "User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"); for (int i = 0; i < headers.length; i++) { httpost.setHeader(headers[i]); } // 设置参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("loginName", "02558771242")); nvps.add(new BasicNameValuePair("loginPwd", "shmily")); UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(nvps, HTTP.UTF_8); // 对自定义请求头进行URL编码 httpost.setEntity(formEntiry); // response = httpclient.execute(httpost); entity = response.getEntity(); System.out.println("POST RESPONSE STATUS: " + response.getStatusLine()); if (entity != null) { System.out.println("RESPONSE BODY: " + EntityUtils.toString(entity)); EntityUtils.consume(entity); } System.out.println("Post logon cookies:"); cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } }