List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:co.paralleluniverse.fibers.dropwizard.MyDropwizardApp.java
@GET @Path("/http") @Timed/*from w w w. j a v a 2 s. c om*/ public String http(@QueryParam("name") Optional<String> name) throws InterruptedException, SuspendExecution, IOException { return httpClient.execute(new HttpGet("http://localhost:8080/?sleep=10&name=" + name.or("name")), new BasicResponseHandler()); }
From source file:fr.lissi.belilif.om2m.rest.WebServiceActions.java
/** * Do get./*from www . j a v a 2s . c om*/ * * @param uri * the uri * @param headers * the headers * @return the string * @throws ClientProtocolException * the client protocol exception * @throws IOException * Signals that an I/O exception has occurred. * @throws HttpResponseException * the http response exception */ public static HttpGetSimpleResp doGet(String uri, HashMap<String, String> headers) throws ClientProtocolException, IOException, HttpResponseException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGetSimpleResp resp = new HttpGetSimpleResp(); try { HttpGet httpGet = new HttpGet(uri); for (String key : headers.keySet()) { httpGet.addHeader(key, headers.get(key)); } CloseableHttpResponse response = httpclient.execute(httpGet); resp.setStatusCode(response.getStatusLine().getStatusCode()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity != null) { // TODO to use for performance in the future // ResponseHandler<String> handler = new BasicResponseHandler(); resp.setResult(new BasicResponseHandler().handleResponse(response)); } EntityUtils.consume(entity); } finally { response.close(); } } else { // TODO optimiz (repeating code) throw new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } finally { httpclient.close(); } return resp; }
From source file:net.anymeta.AnyMetaAPI.java
/** * Execute the given API call onto the anymeta instance, with arguments. * * @param method The method, e.g. "anymeta.user.info" * @param args Arguments to give to the call. * @return A JSONObject or JSONArray with the response. * @throws AnyMetaException//from w w w .ja va2 s .co m */ public Object doMethod(String method, Map<String, Object> args) throws AnyMetaException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("method", method)); params.add(new BasicNameValuePair("format", "json")); convertParameters((Object) args, params, null); String url = this.entrypoint; OAuthConsumer consumer = new CommonsHttpOAuthConsumer(this.ckey, this.csec, SignatureMethod.PLAINTEXT); consumer.setTokenWithSecret(this.tkey, this.tsec); HttpPost request = new HttpPost(url); request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); // set up httppost try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); request.setEntity(entity); } catch (UnsupportedEncodingException e) { throw new AnyMetaException(e.getMessage()); } try { consumer.sign(request); } catch (OAuthMessageSignerException e) { throw new AnyMetaException(e.getMessage()); } catch (OAuthExpectationFailedException e) { throw new AnyMetaException(e.getMessage()); } DefaultHttpClient client = new DefaultHttpClient(); ResponseHandler<String> handler = new BasicResponseHandler(); String response = ""; try { response = client.execute(request, handler); } catch (IOException e) { throw new AnyMetaException(e.getMessage()); } if (response.equalsIgnoreCase("null") || response.equalsIgnoreCase("false")) { return null; } if (!response.startsWith("[") && !response.startsWith("{")) { response = "{\"result\": " + response + "}"; } // System.out.println(response); Object o; try { o = new JSONObject(response); } catch (JSONException e) { try { o = new JSONArray(response); } catch (JSONException e2) { throw new AnyMetaException(e.getMessage() + ": response=" + response); } } if (o instanceof JSONObject && ((JSONObject) o).has("err")) { // handle error try { JSONObject err = ((JSONObject) o).getJSONObject("err").getJSONObject("-attrib-"); throw new AnyMetaException(err.getString("code") + ": " + err.getString("msg")); } catch (JSONException e) { throw new AnyMetaException("Unexpected response in API error: response=" + response); } } return o; }
From source file:com.aokp.romcontrol.github.tasks.DisplayProjectsListTask.java
protected Void doInBackground(Void... unused) { HttpClient httpClient = null;// w w w. ja v a 2 s.c o m try { httpClient = new DefaultHttpClient(); Log.i(TAG, "requesting projects list from url: " + mConfig.REPO_URL + "?page=1&per_page=100"); // request first 30 projects HttpGet requestWebsite = new HttpGet(mConfig.REPO_URL + "?page=1&per_page=100"); // construct that handles relieving web streams to strings ResponseHandler<String> responseHandler = new BasicResponseHandler(); // hold the response in a JSONArray repoProjectsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler)); // debugging if (DEBUG) { Log.d(TAG, "repoProjectsArray.length() is: " + repoProjectsArray.length()); Log.d(TAG, "was invalid test found: " + mFavPackagesStorage.isFavProject("test")); mFavPackagesStorage.addProject("test"); Log.d(TAG, "was valid test found: " + mFavPackagesStorage.isFavProject("test")); mFavPackagesStorage.removeProject("test"); Log.d(TAG, "was invalid test found: " + mFavPackagesStorage.isFavProject("test")); } int projectsReturned = repoProjectsArray.length(); int page = 1; // because we returned the first 100 already while (projectsReturned <= 100) { HttpGet moreProjects = new HttpGet(mConfig.REPO_URL + "?page=" + page++ + "&per_page=100"); // construct that handles recieving web streams to strings ResponseHandler<String> responseHandler_ = new BasicResponseHandler(); // hold the response in a JSONArray JSONArray moreProjectsArray = new JSONArray(httpClient.execute(moreProjects, responseHandler_)); mPrefsList.add(moreProjectsArray); // drop the loop when we find a return with < 100 projects listed if (moreProjectsArray.length() < 100) { if (mProgressDialog != null && mProgressDialog.isShowing()) mProgressDialog.dismiss(); break; } } } catch (JSONException je) { Log.e(TAG, "Bad json interaction...", je); } catch (IOException ioe) { Log.e(TAG, "IOException...", ioe); } catch (NullPointerException ne) { Log.e(TAG, "NullPointer...", ne); } finally { httpClient.getConnectionManager().shutdown(); } return null; }
From source file:sundroid.code.SundroidActivity.java
/** Called when the activity is first created. ***/ @Override/*from w w w . ja va 2 s . co m*/ public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius); Button cmd_submit = (Button) findViewById(R.id.cmd_submit); cmd_submit.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { try { ///////////////// Code to get weather conditions for entered place /////////////////////////////////////////////////// String cityParamString = ((EditText) findViewById(R.id.edit_input)).getText().toString(); String queryString = "https://www.google.com/ig/api?weather=" + cityParamString; queryString = queryString.replace("#", ""); /* Parsing the xml file*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(queryString.replace(" ", "%20")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.d("Sundroid", "parse complete"); WeatherSet ws = gwh.getWeatherSet(); newupdateWeatherInfoView(R.id.weather_today, ws.getWeatherCurrentCondition(), " " + cityParamString, ""); ///////////////// Code to get weather conditions for entered place ends /////////////////////////////////////////////////// ///////////////// Code to get latitude and longitude using zipcode starts /////////////////////////////////////////////////// String latlng_querystring = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + cityParamString.replace(" ", "%20") + "&sensor=false"; URL url_latlng = new URL(latlng_querystring); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); xmlhandler_latlong xll = new xmlhandler_latlong(); xr.setContentHandler(xll); xr.parse(new InputSource(url_latlng.openStream())); Latitude_longitude ll = xll.getLatlng_resultset(); double selectedLat = ll.getLat_lng_pair().getLat(); double selectedLng = ll.getLat_lng_pair().getLon(); ///////////////// Code to get latitude and longitude using zipcode ends /////////////////////////////////////////////////// ///////////////// Code to get miles from text box & convert to meters for passing into the api link//////////////////////// EditText edt = (EditText) findViewById(R.id.edit_miles); float miles = Float.valueOf(edt.getText().toString()); float meters = (float) (miles * 1609.344); ///////////////// Code to get miles from text box & convert to meters for passing into the api link ends ///////////////// ///////////////// Code to pass lat,long and radius and get destinations from places api starts////////// ///////////////// URL queryString_1 = new URL("https://maps.googleapis.com/maps/api/place/search/xml?location=" + Double.toString(selectedLat) + "," + Double.toString(selectedLng) + "&radius=" + Float.toString(meters) + "&types=park|types=aquarium|types=point_of_interest|types=establishment|types=museum&sensor=false&key=AIzaSyDmP0SB1SDMkAJ1ebxowsOjpAyeyiwHKQU"); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); xmlhandler_places xhp = new xmlhandler_places(); xr.setContentHandler(xhp); xr.parse(new InputSource(queryString_1.openStream())); int arraysize = xhp.getVicinity_List().size(); String[] place = new String[25]; String[] place_name = new String[25]; Double[] lat_pt = new Double[25]; Double[] lng_pt = new Double[25]; int i; //Getting name and vicinity tags from the xml file// for (i = 0; i < arraysize; i++) { place[i] = xhp.getVicinity_List().get(i); place_name[i] = xhp.getPlacename_List().get(i); lat_pt[i] = xhp.getLatlist().get(i); lng_pt[i] = xhp.getLonglist().get(i); System.out.println("long -" + lng_pt[i]); place[i] = place[i].replace("#", ""); } ///////////////// Code to pass lat,long and radius and get destinations from places api ends////////// ///////////////// //////////////////////while loop for getting top 5 from the array//////////////////////////////////////////////// int count = 0; int while_ctr = 0; String str_weathercondition; str_weathercondition = ""; WeatherCurrentCondition reftemp; //Places to visit if none of places in the given radius are sunny/clear/partly cloudy String[] rainy_place = { "Indoor Mall", "Watch a Movie", "Go to a Restaurant", "Shopping!" }; double theDistance = 0; String str_dist = ""; while (count < 5) { //Checking if xml vicinity value is empty while (place[while_ctr] == null || place[while_ctr].length() < 2) { while_ctr = while_ctr + 1; } //First search for places that are sunny or clear if (while_ctr < i - 1) { queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr]; System.out.println("In while loop - " + queryString); theDistance = (Math.sin(Math.toRadians(selectedLat)) * Math.sin(Math.toRadians(lat_pt[while_ctr])) + Math.cos(Math.toRadians(selectedLat)) * Math.cos(Math.toRadians(lat_pt[while_ctr])) * Math.cos(Math.toRadians(selectedLng - lng_pt[while_ctr]))); str_dist = new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue() + " miles"; System.out.println(str_dist); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); if (gwh.isIn_error_information()) { System.out.println("Error Info flag set"); } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); // Check if the condition is sunny or partly cloudy if (str_weathercondition.equals("Sunny") || str_weathercondition.equals("Mostly Sunny") || str_weathercondition.equals("Clear")) { System.out.println("Sunny Loop"); // Increment the count ++count; // Disply the place on the widget if (count == 1) { newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr], str_dist); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr], str_dist); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr], str_dist); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr], str_dist); } else if (count == 5) { newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr], str_dist); } else { } } } } // If Five sunny places not found then search for partly cloudy places else if (while_ctr >= i && while_ctr < i * 2) { queryString = "https://www.google.com/ig/api?weather=" + place[while_ctr - i]; queryString = queryString.replace(" ", " "); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); // Use HTTPClient to deal with the URL httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); Log.d(DEBUG_TAG, "parse complete"); if (gwh.isIn_error_information()) { } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); // Check if the condition is sunny or partly cloudy if (str_weathercondition.equals("Partly Cloudy")) { count = count + 1; // Display the place if (count == 1) { newupdateWeatherInfoView(R.id.weather_1, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_2, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_3, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_4, reftemp, place_name[while_ctr - i], str_dist); } else if (count == 5) { newupdateWeatherInfoView(R.id.weather_5, reftemp, place_name[while_ctr - i], str_dist); } else { } } } } //////////////////////////////// Give suggestions for a rainy day else { queryString = "https://www.google.com/ig/api?weather=" + cityParamString; queryString = queryString.replace("#", ""); spf = SAXParserFactory.newInstance(); sp = spf.newSAXParser(); // Get the XMLReader of the SAXParser we created. xr = sp.getXMLReader(); gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); httpclient = new DefaultHttpClient(); httpget = new HttpGet(queryString.replace(" ", "%20")); // create a response handler responseHandler = new BasicResponseHandler(); responseBody = httpclient.execute(httpget, responseHandler); is = new ByteArrayInputStream(responseBody.getBytes()); xr.parse(new InputSource(is)); if (gwh.isIn_error_information()) { } else { ws = gwh.getWeatherSet(); reftemp = ws.getWeatherCurrentCondition(); str_weathercondition = reftemp.getCondition(); if (count == 0) { newupdateWeatherInfoView(R.id.weather_1, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], ""); newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 1) { newupdateWeatherInfoView(R.id.weather_2, reftemp, rainy_place[1], ""); newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[3], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[0], ""); } else if (count == 2) { newupdateWeatherInfoView(R.id.weather_3, reftemp, rainy_place[2], ""); newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 3) { newupdateWeatherInfoView(R.id.weather_4, reftemp, rainy_place[0], ""); newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else if (count == 4) { newupdateWeatherInfoView(R.id.weather_5, reftemp, rainy_place[1], ""); } else { } count = 5; } count = 5; } while_ctr++; } /////////////Closing the soft keypad//////////////// InputMethodManager iMethodMgr = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); iMethodMgr.hideSoftInputFromWindow(edt.getWindowToken(), 0); } catch (Exception e) { resetWeatherInfoViews(); Log.e(DEBUG_TAG, "WeatherQueryError", e); } } }); }
From source file:uf.edu.RegisterUser.java
public void postData() { //Data should be verified before calling this code. no verification done here. // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://128.227.176.22:8182/cgi-bin/putData.py"); try {/* ww w . j a v a 2 s .co m*/ // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("fname", fname)); nameValuePairs.add(new BasicNameValuePair("lname", lname)); nameValuePairs.add(new BasicNameValuePair("email", email)); nameValuePairs.add(new BasicNameValuePair("privacy", privacy)); nameValuePairs.add(new BasicNameValuePair("profile", profile)); nameValuePairs.add(new BasicNameValuePair("mac", macaddress)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httppost, responseHandler).replace('\n', ' ').trim(); //JSONObject response=new JSONObject(responseBody); Log.i(TAG, "Registration Response: " + responseBody); if (responseBody.compareToIgnoreCase("success") == 0) { Toast.makeText(this, "Registration Successful", Toast.LENGTH_LONG).show(); } else if (responseBody.compareToIgnoreCase("Error: duplicate record") == 0) { Toast.makeText(this, "Already Registered", Toast.LENGTH_LONG).show(); } else if (responseBody.substring(0, 25 > responseBody.length() ? responseBody.length() : 25) .compareToIgnoreCase("Note: changing owner from") == 0) { Toast.makeText(this, "Moved already registered device to your account", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show(); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } }
From source file:dk.i2m.drupal.resource.NodeResource.java
public List<FileMessage> loadFiles(Long id) throws HttpResponseException, IOException { URLBuilder builder = new URLBuilder(getDc().getHostname()); builder.add(getDc().getEndpoint());/* www . j a v a 2 s .co m*/ builder.add(getAlias()); builder.add(id); builder.add("files"); // Do not return the file contents (saves bandwidth) builder.add(0); HttpGet method = new HttpGet(builder.toURI()); ResponseHandler<String> handler = new BasicResponseHandler(); String response = getDc().getHttpClient().execute(method, handler); return new Gson().fromJson(response, new TypeToken<List<FileMessage>>() { }.getType()); }
From source file:com.contextawareframework.querymodule.BaseQueryClass.java
private String checkApi() { /*String devEmail = "test123@gmail.com"; String apiKey = "a975d70e-bebc-4270-8160-d71fa5241bd2"; //a975d70e-bebc-4270-8160-d71fa5241bd2 correct api key String pkgName = "com.test";/*from w ww.j a va 2 s .c om*/ String appId = "com.testtestApp";*/ String response = null; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://10.184.0.132:8005/ContextAwareFrameworkWebService/apiCheckTest1"); Log.d("Debug", "test1"); // set values you'd like to send List pairs = new ArrayList(); pairs.add(new BasicNameValuePair("devEmail", developerEmail)); pairs.add(new BasicNameValuePair("apiKey", ApiKey)); pairs.add(new BasicNameValuePair("pkgName", appPkgName)); pairs.add(new BasicNameValuePair("appId", appId)); pairs.add(new BasicNameValuePair("userEmail", userEmailId)); pairs.add(new BasicNameValuePair("userdeviceId", deviceId)); pairs.add(new BasicNameValuePair("random", "randomConstant")); try { post.setEntity(new UrlEncodedFormEntity(pairs)); // set ResponseHandler to handle String responses ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); serverRequestStatus = true; serverStatus = response; Log.v("HttpPost", "Response: " + serverStatus); } catch (Exception e) { Log.e("Debug", "Error in post method"); e.printStackTrace(); } return response; }
From source file:com.taqueue.connection.QueueConnectionManager.java
/** * Sends a POST to the queue with the parameters nvps, returns the result. * @param nvps the NameValuePair of parameters to be sent to the queue server * @return ConnectionResult containing the status code for the attempt and the message returned * message will be null iff the status is not OK */// w w w . j av a2 s .c o m private ConnectionResult sendMessage(List<NameValuePair> nvps) { ConnectionResult res = new ConnectionResult(); //default to OK, we'll change in the event of an error res.status = ConnectionStatus.OK; HttpPost post = new HttpPost(HOST + PATH); //DefaultHttpClient client = new DefaultHttpClient(); //set up the timeout HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT); // set up the connection manager if needed if (manager == null) { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); manager = new ThreadSafeClientConnManager(httpParams, registry); } DefaultHttpClient client = new DefaultHttpClient(manager, httpParams); try { //set up our POST values post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); //send it along ResponseHandler<String> handler = new BasicResponseHandler(); connectionWatcher watcher = new connectionWatcher(post); Thread t = new Thread(watcher); t.start(); res.message = client.execute(post, handler); watcher.finished(); //and clean up //if any exceptions are thrown return a connection error result } catch (Exception e) { res.status = ConnectionStatus.CONNECTION_ERROR; res.message = null; } finally { post.abort(); } return res; }
From source file:ca.sqlpower.wabit.enterprise.client.ServerInfoProvider.java
private static void init(String host, String port, String path, String username, String password) throws IOException { URL serverInfoUrl = toServerInfoURL(host, port, path); if (version.containsKey(generateServerKey(host, port, path, username, password))) return;/*from ww w.j a va 2 s . c om*/ try { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 2000); DefaultHttpClient httpClient = new DefaultHttpClient(params); httpClient.setCookieStore(WabitClientSession.getCookieStore()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(serverInfoUrl.getHost(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); HttpUriRequest request = new HttpOptions(serverInfoUrl.toURI()); String responseBody = httpClient.execute(request, new BasicResponseHandler()); // Decode the message String serverVersion; Boolean licensedServer; final String watermarkMessage; try { JSONObject jsonObject = new JSONObject(responseBody); serverVersion = jsonObject.getString(ServerProperties.SERVER_VERSION.toString()); licensedServer = jsonObject.getBoolean(ServerProperties.SERVER_LICENSED.toString()); watermarkMessage = jsonObject.getString(ServerProperties.SERVER_WATERMARK_MESSAGE.toString()); } catch (JSONException e) { throw new IOException(e.getMessage()); } // Save found values version.put(generateServerKey(host, port, path, username, password), new Version(serverVersion)); licenses.put(generateServerKey(host, port, path, username, password), licensedServer); watermarkMessages.put(generateServerKey(host, port, path, username, password), watermarkMessage); // Notify the user if the server is not licensed. if (!licensedServer) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(null, watermarkMessage, "SQL Power Wabit Server License", JOptionPane.WARNING_MESSAGE); } }); } // Now get the available fonts. URL serverFontsURL = toServerFontsURL(host, port, path); HttpUriRequest fontsRequest = new HttpGet(serverFontsURL.toURI()); String fontsResponseBody = httpClient.execute(fontsRequest, new BasicResponseHandler()); try { JSONArray fontsArray = new JSONArray(fontsResponseBody); List<String> fontNames = new ArrayList<String>(); for (int i = 0; i < fontsArray.length(); i++) { fontNames.add(fontsArray.getString(i)); } // Sort the list. Collections.sort(fontNames); fonts.put(generateServerKey(host, port, path, username, password), fontNames); } catch (JSONException e) { throw new IOException(e.getMessage()); } } catch (URISyntaxException e) { throw new IOException(e.getLocalizedMessage()); } }