public static String postStream2(String url, String data) { InputStream is = null; String flag = ""; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(data)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse httpResponse = httpClient.execute(httpPost); Log.i("Httpresponse:", httpResponse.toString()); Log.i("Http Response:", String.valueOf(httpResponse.getStatusLine().getStatusCode())); if (String.valueOf(httpResponse.getStatusLine().getStatusCode()).trim().equals("404")) { flag = "false"; } else { flag = "true"; } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (IOException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } Log.e("is:", is.toString()); return flag; }
public static String postStream(String url, String data) { InputStream is = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(data)); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse httpResponse = httpClient.execute(httpPost); Log.i("Httpresponse:", httpResponse.toString()); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (ClientProtocolException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } catch (IOException e) { e.printStackTrace(); Log.e("JSON post error:", e.toString()); } Log.e("is:", is.toString()); return readStream(is); }
@Override protected String doInBackground(String... urls) { Log.d("DEBUG", "Inside dwp"); String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; Log.d("DEBUG", s); } } catch (Exception e) { e.printStackTrace(); Log.d("DEBUG", "Exception"); } } Log.d("DEBUG", "Done dwp"); return response; }
// ***************************************************************************** // Delete Contact using HTTP DELETE method with singleContactUrl. // ***************************************************************************** public Integer DeleteContact(Contact deleteContact) { Integer statusCode = 0; HttpResponse response; try { boolean isValid = true; // Data validation goes here if (isValid) { HttpDelete request = new HttpDelete(singleContactUrl + deleteContact.getId()); request.setHeader("User-Agent", "dev.ronlemire.contactClient"); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); // Send request to WCF service DefaultHttpClient httpClient = new DefaultHttpClient(); response = httpClient.execute(request); Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode()); statusCode = response.getStatusLine().getStatusCode(); } } catch (Exception e) { e.printStackTrace(); } return statusCode; }
@Override protected String doInBackground(Void... voids) { try { DefaultHttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet("http://49.212.148.198/imagetw/list.php?list=10"); res = client.execute( get, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse responce) throws ClientProtocolException, IOException { switch (responce.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: // Log.d("API","データあったよー"); return EntityUtils.toString(responce.getEntity(), "UTF-8"); case HttpStatus.SC_NOT_FOUND: throw new RuntimeException("データが無いです"); default: throw new RuntimeException("通信エラー"); } } }); } catch (ClientProtocolException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return res; }
private String spejdPost(JsonObject jo) { @SuppressWarnings({"resource"}) DefaultHttpClient httpclient = new DefaultHttpClient(); HttpResponse resp; HttpPost httpPost = new HttpPost(SPEJD_SERVICE_POST); httpPost.addHeader("Content-Type", "application/json"); StringEntity reqEntity = null; try { reqEntity = new StringEntity(jo.toString()); } catch (UnsupportedEncodingException e) { System.out.println(e.toString()); } assert reqEntity != null; httpPost.setEntity(reqEntity); try { resp = httpclient.execute(httpPost); return EntityUtils.toString(resp.getEntity()); } catch (IOException e) { e.printStackTrace(); } return null; }
/** * 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); }
protected MjpegInputStream doInBackground(String... url) { // TODO: if camera has authentication deal with it and don't just not work HttpResponse res = null; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 5 * 1000); if (DEBUG) Log.d(TAG, "1. Sending http request"); try { res = httpclient.execute(new HttpGet(URI.create(url[0]))); if (DEBUG) Log.d(TAG, "2. Request finished, status = " + res.getStatusLine().getStatusCode()); if (res.getStatusLine().getStatusCode() == 401) { // You must turn off camera User Access Control before this will work return null; } return new MjpegInputStream(res.getEntity().getContent()); } catch (ClientProtocolException e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "Request failed-ClientProtocolException", e); } // Error connecting to camera } catch (IOException e) { if (DEBUG) { e.printStackTrace(); Log.d(TAG, "Request failed-IOException", e); } // Error connecting to camera } return null; }
public HttpUtils(int connTimeout, String userAgent) { HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, connTimeout); HttpConnectionParams.setSoTimeout(params, connTimeout); HttpConnectionParams.setConnectionTimeout(params, connTimeout); if (TextUtils.isEmpty(userAgent)) { userAgent = OtherUtils.getUserAgent(null); } HttpProtocolParams.setUserAgent(params, userAgent); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10)); ConnManagerParams.setMaxTotalConnections(params, 10); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 1024 * 8); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443)); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES)); httpClient.addRequestInterceptor( new HttpRequestInterceptor() { @Override public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException { if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) { httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); httpClient.addResponseInterceptor( new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GZipDecompressingEntity(response.getEntity())); return; } } } } }); }
public String getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } json = sb.toString(); is.close(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return json; }
@Override protected Person doInBackground(String... params) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(WebStuff.USER_URL + "?email=" + params[0]); HttpResponse response = httpClient.execute(httpGet); Log.i("Cheerspal", response.getStatusLine().toString()); HttpEntity httpEntity = response.getEntity(); String result = EntityUtils.toString(httpEntity); if (result != null) { Log.i("Cheerspal", "result: " + result); JsonObject responseObject = new JsonParser().parse(result).getAsJsonObject(); String firstName = responseObject.get("firstname").getAsString(); String lastName = responseObject.get("lastname").getAsString(); return new Person(firstName, lastName, params[0]); } else { Log.i("Cheerspal", "result: null"); } } catch (Exception e) { } return null; }
private InputStream getUrlData(String url) throws URISyntaxException, ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); HttpGet method = new HttpGet(new URI(url)); HttpResponse res = client.execute(method); return res.getEntity().getContent(); }
protected final String invoke_delete_string(String url) throws IOException { DefaultHttpClient dhc = new DefaultHttpClient(); try { set_basic_auth(dhc); Log.i(_module_name, "DELETE: " + url); HttpDelete delete = new HttpDelete(url); sign_auth(delete); HttpResponse httpResponse = dhc.execute(delete); int statusCode = httpResponse.getStatusLine().getStatusCode(); String res = UHttpComponents.loadStringFromHttpResponse(httpResponse); if (!is_ok_status(statusCode)) { String phrase = httpResponse.getStatusLine().getReasonPhrase(); String msg = String.format("DELETE*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url); throw new HttpIOException(msg, delete, statusCode, phrase, res); } Log.i( _module_name, String.format("DELETE-OK: %s <= %s", make_log_message(res.toString()), url)); return res; } catch (IOException e) { Log.w(_module_name, String.format("DELETE*IO: %s <= %s", e.getMessage(), url), e); throw e; } catch (Throwable e) { Log.w(_module_name, String.format("DELETE*Throwable: %s <= %s", e.getMessage(), url), e); throw new InvocationTargetIOException(e); } finally { dhc.getConnectionManager().shutdown(); } }
protected final String invoke_put_string(String url, Bundle params) throws IOException { DefaultHttpClient dhc = new DefaultHttpClient(); try { set_basic_auth(dhc); Log.i(_module_name, "PUT: " + url); HttpPut put = new HttpPut(url); sign_auth(put); if (params != null) { ArrayList<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { nvps.add(new BasicNameValuePair(key, params.getString(key))); } UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(nvps, "UTF-8"); put.setEntity(reqEntity); } HttpResponse httpResponse = dhc.execute(put); int statusCode = httpResponse.getStatusLine().getStatusCode(); String res = UHttpComponents.loadStringFromHttpResponse(httpResponse); if (!is_ok_status(statusCode)) { String phrase = httpResponse.getStatusLine().getReasonPhrase(); String msg = String.format("PUT*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url); throw new HttpIOException(msg, put, statusCode, phrase, res); } Log.i(_module_name, String.format("PUT-OK: %s <= %s", make_log_message(res.toString()), url)); return res; } catch (IOException e) { Log.w(_module_name, String.format("PUT*IO: %s <= %s", e.getMessage(), url), e); throw e; } catch (Throwable e) { Log.w(_module_name, String.format("PUT*Throwable: %s <= %s", e.getMessage(), url), e); throw new InvocationTargetIOException(e); } finally { dhc.getConnectionManager().shutdown(); } }
protected final JSONObject invoke_get_json(String url) throws IOException { DefaultHttpClient dhc = new DefaultHttpClient(); try { set_basic_auth(dhc); Log.i(_module_name, "GET: " + url); HttpGet get = new HttpGet(url); sign_auth(get); HttpResponse httpResponse = dhc.execute(get); int statusCode = httpResponse.getStatusLine().getStatusCode(); String res = UHttpComponents.loadStringFromHttpResponse(httpResponse); if (!is_ok_status(statusCode)) { String phrase = httpResponse.getStatusLine().getReasonPhrase(); String msg = String.format("GET*STATUS: [%s:%s] %s <= %s", statusCode, phrase, res, url); throw new HttpIOException(msg, get, statusCode, phrase, res); } Log.i(_module_name, String.format("GET-OK: %s <= %s", make_log_message(res), url)); return new JSONObject(res); } catch (JSONException e) { Log.w(_module_name, String.format("GET*JSON: %s <= %s", e.getMessage(), url), e); throw new IOException(e.getMessage()); } catch (IOException e) { Log.w(_module_name, String.format("GET*IO: %s <= %s", e.getMessage(), url), e); throw e; } catch (Throwable e) { Log.w(_module_name, String.format("GET*Throwable: %s <= %s", e.getMessage(), url), e); throw new InvocationTargetIOException(e); } finally { dhc.getConnectionManager().shutdown(); } }
/** * Fetches data from Steam Web API using the specified interface, method and version. Additional * parameters are supplied via HTTP GET. Data is returned as a String in the given format. * * @param apiInterface The Web API interface to call, e.g. <code>ISteamUser</code> * @param format The format to load from the API ("json", "vdf", or "xml") * @param method The Web API method to call, e.g. <code>GetPlayerSummaries</code> * @param params Additional parameters to supply via HTTP GET * @param version The API method version to use * @return Data is returned as a String in the given format (which may be "json", "vdf", or * "xml"). * @throws WebApiException In case of any request failure */ public static String load( String format, String apiInterface, String method, int version, Map<String, Object> params) throws WebApiException { String protocol = secure ? "https" : "http"; String url = String.format( "%s://api.steampowered.com/%s/%s/v%04d/?", protocol, apiInterface, method, version); if (params == null) { params = new HashMap<String, Object>(); } params.put("format", format); if (apiKey != null) { params.put("key", apiKey); } boolean first = true; for (Map.Entry<String, Object> param : params.entrySet()) { if (first) { first = false; } else { url += '&'; } url += String.format("%s=%s", param.getKey(), param.getValue()); } if (LOG.isInfoEnabled()) { String debugUrl = (apiKey == null) ? url : url.replace(apiKey, "SECRET"); LOG.info("Querying Steam Web API: " + debugUrl); } String data; try { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, false); HttpGet request = new HttpGet(url); HttpResponse response = httpClient.execute(request); Integer statusCode = response.getStatusLine().getStatusCode(); if (!statusCode.toString().startsWith("20")) { if (statusCode == 401) { throw new WebApiException(WebApiException.Cause.UNAUTHORIZED); } throw new WebApiException( WebApiException.Cause.HTTP_ERROR, statusCode, response.getStatusLine().getReasonPhrase()); } data = EntityUtils.toString(response.getEntity()); } catch (WebApiException e) { throw e; } catch (Exception e) { throw new WebApiException("Could not communicate with the Web API.", e); } return data; }
private InputStream retrieveConfigurationFileFromRemoteRepository() throws Exception { if (configFileURL.getProtocol().startsWith("http")) { HttpGet httpGet = new HttpGet(configFileURL.toURI()); DefaultHttpClient client = new DefaultHttpClient(); configureProxy(client); HttpResponse httpResponse = client.execute(httpGet); switch (httpResponse.getStatusLine().getStatusCode()) { case 200: log.debug("Connected to repository! Getting available Stacks"); break; case 404: log.error("Failed! (Config file not found: " + configFileURL + ")"); return null; default: log.error( "Failed! (server returned status code: " + httpResponse.getStatusLine().getStatusCode()); return null; } return httpResponse.getEntity().getContent(); } else if (configFileURL.getProtocol().startsWith("file")) { return new FileInputStream(new File(configFileURL.toURI())); } return null; }
public String getJSONFromUrl(String url) { // Making HTTP request try { HttpParams httpParameters = new BasicHttpParams(); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpGet httpPost = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); returnJsonAsString = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return returnJsonAsString; }
public void run() { String url = new ConversionUrlGenerator().generateUrlString(TRACK_HOST); Log.d("MoPub", "Conversion track: " + url); DefaultHttpClient httpClient = HttpClientFactory.create(); HttpResponse response; try { HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); } catch (Exception e) { Log.d("MoPub", "Conversion track failed [" + e.getClass().getSimpleName() + "]: " + url); return; } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Log.d("MoPub", "Conversion track failed: Status code != 200."); return; } HttpEntity entity = response.getEntity(); if (entity == null || entity.getContentLength() == 0) { Log.d("MoPub", "Conversion track failed: Response was empty."); return; } // If we made it here, the request has been tracked Log.d("MoPub", "Conversion track successful."); mSharedPreferences.edit().putBoolean(mIsTrackedKey, true).commit(); }
/** * HttpClient方式实现,支持验证指定证书 * * @throws ClientProtocolException * @throws IOException */ public void initSSLCertainWithHttpClient() throws ClientProtocolException, IOException { int timeOut = 30 * 1000; HttpParams param = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(param, timeOut); HttpConnectionParams.setSoTimeout(param, timeOut); HttpConnectionParams.setTcpNoDelay(param, true); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", TrustCertainHostNameFactory.getDefault(this), 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(param, registry); DefaultHttpClient client = new DefaultHttpClient(manager, param); // HttpGet request = new // HttpGet("https://certs.cac.washington.edu/CAtest/"); HttpGet request = new HttpGet("https://www.alipay.com/"); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); StringBuilder result = new StringBuilder(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } Log.e("HTTPS TEST", result.toString()); }
public JSONObject makeHttpRequest(String url, List<NameValuePair> params) { // Making HTTP request try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // Depends on your web service httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStreamReader isr = new InputStreamReader(httpEntity.getContent()); BufferedReader reader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "::::Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "::::Error parsing data " + e.toString()); } return jObj; }
static void testBasicAuth() throws ClientProtocolException, IOException { HttpHost targetHost = new HttpHost("localhost", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient .getCredentialsProvider() .setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("newuser", "tomcat")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("/simpleweb/protected"); System.out.println(httpget.getURI()); HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine().getStatusCode()); String charset = HttpclientTutorial.getResponseCharset(response); HttpclientTutorial.output(entity, charset); EntityUtils.consume(entity); }
// This method is executed in the background thread on our Survey object private String uploadSurveyData(String myXML) { // Set up communication with the server DefaultHttpClient client = new DefaultHttpClient(); String result = null; // HttpPost httpPost; httpPost = new HttpPost( "http://YOUR DOMAIN HERE/survey-webApp/index.php/webUser_Controllers/android_controller/save_survey_xml"); try { // Encode the xml, add header and set it to POST request StringEntity entity = new StringEntity(myXML, HTTP.UTF_8); // entity.setContentType("text/xml"); httpPost.setEntity(entity); // Execute POST request and get response HttpResponse response = client.execute(httpPost); HttpEntity responseEntity = response.getEntity(); // System.out.print(EntityUtils.toString(responseEntity)); // Set up XML parsing objects SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); // Set up an instance of our class to parse the status response HttpResponseHandler myResponseHandler = new HttpResponseHandler(); xr.setContentHandler(myResponseHandler); xr.parse(retrieveInputStream(responseEntity)); // check myResponseHandler for response result = myResponseHandler.getStatus(); } catch (Exception e) { result = "Exception - " + e.getMessage(); } return result; }
@Override public SignInDTO signIn(String userName, String pass, String authTokenType) throws Exception { String url = "http://113.160.50.84:1009/testing/ica467/trunk/public/auth-rest"; DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("username", userName)); urlParameters.add(new BasicNameValuePair("password", pass)); urlParameters.add(new BasicNameValuePair("grant_type", "password")); urlParameters.add(new BasicNameValuePair("client_id", "123456789")); urlParameters.add(new BasicNameValuePair("type", "password")); urlParameters.add(new BasicNameValuePair("email", "123456789")); httpPost.setEntity(new UrlEncodedFormEntity(urlParameters)); try { HttpResponse response = httpClient.execute(httpPost); String responseStr = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = new JSONObject(responseStr); SignInDTO signInDTO = null; if (jsonObject.has("code") && (Integer) jsonObject.get("code") == 400) { Log.d(TAG, "sign in fail"); } else { Log.d(TAG, "sign in successful"); signInDTO = new Gson().fromJson(responseStr.toString(), SignInDTO.class); } return signInDTO; } catch (IOException e) { e.printStackTrace(); } return null; }
@Override public void insertOrUpdatePreferences(EasitApplicationPreferences preferences, EasitAccount user) throws Exception { // Convert the prefs to String strPrefs = localPrefsToServerPrefs(preferences); // Prepare request and send it DefaultHttpClient client = new DefaultHttpClient(); StringEntity input = new StringEntity(strPrefs); input.setContentEncoding("UTF8"); input.setContentType("application/json"); HttpPost postRequest = new HttpPost( environment.getProperty("flowManager.url") + "/oldpreferences/" + user.getUserToken()); postRequest.setEntity(input); HttpResponse response = client.execute(postRequest); // NOT Correct answer if (response.getStatusLine().getStatusCode() != 200) { logger.info("ERROR:"); logger.info( "URL target" + environment.getProperty("flowManager.url") + "/oldpreferences/" + user.getUserToken()); throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } // Clear connection client.getConnectionManager().shutdown(); }
/** * Getting XML from URL making HTTP request * * @param url string */ public String getXmlFromUrl(String url) { String xml = null; DefaultHttpClient httpClient = new DefaultHttpClient(); try { // defaultHttpClient HttpGet httpPost = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); xml = EntityUtils.toString(httpEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NetworkOnMainThreadException e) { e.printStackTrace(); } // return XML return xml; }
public PreguntasPojo llamarServicioPreguntas() throws IOException { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(Constantes.URL_SERVICIOS); ResponseHandler handler = darResponseHandler(); PreguntasPojo preguntasPojo = (PreguntasPojo) httpclient.execute(httpget, handler); return preguntasPojo; }
/** Creates the client executor that will be used by RESTEasy when making the request. */ private ClientExecutor createClientExecutor() { // TODO I think the http client is thread safe - so let's try to create just one of these DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.addRequestInterceptor( new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { Locale l = getLocale(); if (l == null) { l = Locale.getDefault(); } request.addHeader("Accept-Language", l.toString()); // $NON-NLS-1$ } }); if (this.authProvider != null) { httpClient.addRequestInterceptor( new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { authProvider.provideAuthentication(request); } }); } return new ApacheHttpClient4Executor(httpClient); }
private static HttpClient createHttpClient( String host, int port, String username, String password) { PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool); SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try { schemeRegistry.register( new Scheme( "https", 443, new SSLSocketFactory( new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()))); } catch (Exception e) { throw new RuntimeException(e); } httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true)); httpClient .getCredentialsProvider() .setCredentials( new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); return httpClient; }
public String queryStation( Context context, Handler uiHandler, String stationCode, VechileType type) { // XXX do not create client every time, use HTTP1.1 keep-alive! final DefaultHttpClient client = new DefaultHttpClient(); loadCookiesFromPreferences(context, client); // Create a response handler String result = null; try { do { final HttpPost request = createRequest(context, uiHandler, client, stationCode, previousResponse, type); result = client.execute(request, new BasicResponseHandler()); previousResponse = result; saveCookiesToPreferences(context, client); } while (!result.contains(HAS_RESULT) && !result.contains(NO_INFO)); if (result.contains(NO_INFO)) { result = context.getResources().getString(error_retrieveEstimates_matching_noInfo); } } catch (Exception e) { Log.e(TAG, "Could not get data for station " + stationCode, e); } finally { // XXX do not create client every time, use HTTP1.1 keep-alive! client.getConnectionManager().shutdown(); } return result; }