List of usage examples for java.net MalformedURLException printStackTrace
public void printStackTrace()
From source file:com.bazaarvoice.BazaarRequest.java
/** * Post a submission, spawn a thread, and return the response via the * listener. (non-blocking)//w ww . ja v a 2 s . co m * * @param type * the type of request * @param params * the parameters for the request * @param listener * the listener to handle the results on * @throws BazaarException */ public void postSubmission(final RequestType type, BazaarParams params, final OnBazaarResponse listener) { String requestString = requestUrl + type.getSubmissionName() + ".json"; try { this.url = new URL(requestString); } catch (MalformedURLException e) { e.printStackTrace(); } if (params != null) { this.mediaEntity = params.getMedia(); if (this.mediaEntity != null) { params.addPostParameters(apiVersion, passKey, this); if (this.mediaEntity.getFile() != null) { params.addMultipartParameter(mediaEntity.getName(), mediaEntity.getFilename(), mediaEntity.getFile(), this); } else { params.addMultipartParameter(mediaEntity.getName(), mediaEntity.getFilename(), mediaEntity.getBytes(), this); } } else { paramString = params.toURL(apiVersion, passKey); } } this.listener = listener; new AsyncTransaction().execute("POST"); }
From source file:com.beesham.popularmovies.sync.MoviesSyncAdapter.java
@Override public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {/*from w ww . ja va2s . co m*/ HttpURLConnection urlConnection = null; BufferedReader reader = null; String moviesJsonStr = null; try { final String MOVIES_BASE_URL = getContext().getString(R.string.movies_base_url); final String API_KEY_PARAM = "api_key"; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); String sort_by = prefs.getString(getContext().getString(R.string.pref_sort_key), getContext().getString(R.string.pref_sort_default)); Uri builtUri = Uri.parse(MOVIES_BASE_URL).buildUpon().appendPath(sort_by) .appendQueryParameter(API_KEY_PARAM, API_KEY).build(); URL url = new URL(builtUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(15000); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) return; reader = new BufferedReader((new InputStreamReader(inputStream))); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) return; moviesJsonStr = buffer.toString(); getMovieDataFromJson(moviesJsonStr); } catch (MalformedURLException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) urlConnection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } } } }
From source file:com.beesham.popularmovies.sync.MoviesSyncAdapter.java
/** * Gets and stores the movie trailer and reviews JSON data * @param movieId/*from w w w . ja v a 2s.com*/ * @param flag * @return */ private String getTrailersOrReviews(String movieId, int flag) { HttpURLConnection urlConnection = null; BufferedReader reader = null; String movieJsonStr = null; String MOVIE_QUERY_URL = null; try { switch (flag) { case 0: MOVIE_QUERY_URL = getContext().getString(R.string.movies_base_trailers_url, movieId); break; case 1: MOVIE_QUERY_URL = getContext().getString(R.string.movies_base_reviews_url, movieId); break; } final String API_KEY_PARAM = "api_key"; Uri builtUri = Uri.parse(MOVIE_QUERY_URL).buildUpon().appendQueryParameter(API_KEY_PARAM, API_KEY) .build(); URL url = new URL(builtUri.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setConnectTimeout(10000); urlConnection.setReadTimeout(15000); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); if (inputStream == null) return null; reader = new BufferedReader((new InputStreamReader(inputStream))); String line; while ((line = reader.readLine()) != null) { buffer.append(line + "\n"); } if (buffer.length() == 0) return null; movieJsonStr = buffer.toString(); } catch (MalformedURLException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } finally { if (urlConnection != null) urlConnection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } } } return movieJsonStr; }
From source file:com.liveneo.plat.web.action.DownloadAction.java
public InputStream getInputStream() throws UnsupportedEncodingException, FileNotFoundException { // attachment,?,??;inline,??,? String file = ""; if (StringUtils.equalsIgnoreCase(loadflag, "restore")) { file = CreateXml.backuptarget + fileName + ".zip"; }//from ww w . j a v a 2s . c om if (StringUtils.equalsIgnoreCase(loadflag, "excel")) { file = getServletContext().getRealPath("/WEB-INF/pages/template/" + fileName); } if (StringUtils.equalsIgnoreCase(loadflag, "recording")) { HttpURLConnection connection = null; try { URL url = new URL(fileName); connection = (HttpURLConnection) url.openConnection(); connection.connect(); // BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); this.getResponse().setHeader("application/x-msdownload", "attachment;file=" + java.net.URLEncoder.encode(file, "UTF-8")); return new BufferedInputStream(connection.getInputStream()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println(getServletContext().getRealPath("/noneccrecord/ivrvoice/")+"/"+StringUtils.substringAfter(fileName, "/opt/AppServer/tomcat/webapps/noneccrecord/ivrvoice/")); // file="D:/apache-tomcat-6.0.35/webapps/npworkplat/noneccrecord/ivrvoice/file1680475804236541293_ivrvoice.wav"; } if (StringUtils.equalsIgnoreCase(loadflag, "license")) { file = fileName; } if (StringUtils.equalsIgnoreCase(loadflag, "wo")) { WorkOrderAction w = new WorkOrderAction(); List<Workorder> ws = new ArrayList<Workorder>(); ws = (List<Workorder>) this.getSession().getAttribute(sessionname); if (ws.size() > 0) { this.createWorkorderExcel(getServletContext().getRealPath("/excel/wo_info.xls"), ws, "??"); } file = getServletContext().getRealPath("/excel/") + "/" + fileName; System.out.println("file:" + file); } // if (StringUtils.equalsIgnoreCase(loadflag, "report")) { String title = this.getRequest().getParameter("title"); title = java.net.URLDecoder.decode(title, "UTF-8"); title = java.net.URLDecoder.decode(title, "UTF-8"); String tvalue = this.getRequest().getParameter("tvalue"); // String[] titles = title.split(","); //?trtd List<List<String>> tds = new ArrayList<List<String>>(); String[] tr = tvalue.split(";"); for (int j = 0; j < tr.length; j++) { List<String> td = new ArrayList<String>(); String[] fields = tr[j].split(","); for (String v : fields) { if (v == null) { v = ""; } td.add(v); } tds.add(td); } //?excel ExcelUtils.exportExcel(getServletContext().getRealPath("/excel/") + "/" + fileName, titles, tds); file = getServletContext().getRealPath("/excel/") + "/" + fileName; } //? if (StringUtils.equalsIgnoreCase(loadflag, "commonexcel")) { String title = this.getRequest().getParameter("title"); title = java.net.URLDecoder.decode(title, "UTF-8"); title = java.net.URLDecoder.decode(title, "UTF-8"); // String[] titles = title.split(","); //?trtd List<List<String>> tds = new ArrayList<List<String>>(); tds = (List<List<String>>) this.getSession().getAttribute(sessionname); //?excel ExcelUtils.exportExcel(getServletContext().getRealPath("/excel/") + "/" + fileName, titles, tds); file = getServletContext().getRealPath("/excel/") + "/" + fileName; } this.getResponse().setHeader("application/x-msdownload", "attachment;file=" + java.net.URLEncoder.encode(file, "UTF-8")); // fileName? return new BufferedInputStream(new FileInputStream(file)); }
From source file:com.example.httpjson.AppEngineClient.java
public void delete(URL uri, Map<String, List<String>> headers) { URL url = null;//from w ww . java 2s . c o m try { url = new URL("http://localhost:8080/deleteservice"); } catch (MalformedURLException exception) { exception.printStackTrace(); } HttpURLConnection httpURLConnection = null; try { httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestMethod("DELETE"); System.out.println("DELETE response code..! " + httpURLConnection.getResponseCode()); } catch (IOException exception) { exception.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } }
From source file:com.example.savedollars.ProductTotalPriceDisplay.java
private void getProductDetails(String barcodeNumber) { // Smita//from w w w. j a va 2 s . co m String baseURL = getString(R.string.searchURL); String key = getString(R.string.key); String country = getString(R.string.country); String urlString = baseURL + "&" + key + "&" + country + "&" + "q=" + barcodeNumber; try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder out = new StringBuilder(); String line; String data; while ((line = reader.readLine()) != null) { out.append(line); } // JSON data stored as string. data = out.toString(); System.out.println("Bets: JSON DATA :" + data); // product // information from // google API in parseJsonData(data); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.gottibujiku.httpjsonexchange.main.HttpJSONExchange.java
/** * This method sends a GET request to the server. * It prepares the request by creating a valid URL with a query string(if any) * then adds the headers and then open a connection to the server; retrieves * response and return result as a JSON Object * //from w w w .j a va2 s . co m * @return a JSON object containing the response */ public JSONObject sendGETRequest() { /* 1. Form the query string by concatenating param names and their values * 2. Add HTTP headers to the request and set request method to GET * 3. Open stream and read server response * */ if (fullDomainName == null) { throw new NullPointerException("No URL provided! Please provide one!");//No domain name was provided } JSONObject jsonResponse = null; URL url = null;//a url object to hold a complete URL try { url = new URL(fullDomainName + QUERY_SEPARATOR + getFormatedQueryString(queryParams));//a complete URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = addHeadersToRequest(headers, connection);//add headers to connection and get modified instance connection.setRequestProperty("Accept-Charset", UTF_CHARSET);//accept the given encoding //a call to connection.connect() is superfluous since connect will be called //implicitly when the stream is opened connection.setRequestMethod("GET"); String jsonString = getServerResponse(connection); connection.disconnect(); jsonResponse = new JSONObject(jsonString);//change the response into a json object } catch (MalformedURLException e) { e.printStackTrace(); return null;//return if the URL is malformed } catch (IOException e) { e.printStackTrace(); return null;//if failed to open a connection } catch (JSONException e) { e.printStackTrace(); return null;//invalid JSON response } return jsonResponse; }
From source file:com.gottibujiku.httpjsonexchange.main.HttpJSONExchange.java
/** * This method sends a GET request to the server. * It prepares the request by creating a valid URL with a query string(if any) * then adds the headers and then open a connection to the server; retrieves * response and return result as a JSON Object * /*w w w.java 2 s.com*/ * * @param fullDomainName a fully qualified domain name including the protocol * @param queryParams parameters to be sent in the query string * @param headers additional headers * @return a JSON object containing the response */ public JSONObject sendGETRequest(String fullDomainName, HashMap<String, String> queryParams, HashMap<String, String> headers) { /* 1. Form the query string by concatenating param names and their values * 2. Add HTTP headers to the request and set request method to GET * 3. Open stream and read server response * */ if (fullDomainName == null) { throw new NullPointerException("No URL provided! Please provide one!");//No domain name was provided } JSONObject jsonResponse = null; URL url = null;//a url object to hold a complete URL try { url = new URL(fullDomainName + QUERY_SEPARATOR + getFormatedQueryString(queryParams));//a complete URL HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection = addHeadersToRequest(headers, connection);//add headers to connection and get modified instance connection.setRequestProperty("Accept-Charset", UTF_CHARSET);//accept the given encoding //a call to connection.connect() is superfluous since connect will be called //implicitly when the stream is opened connection.setRequestMethod("GET"); String jsonString = getServerResponse(connection); connection.disconnect(); jsonResponse = new JSONObject(jsonString);//change the response into a json object } catch (MalformedURLException e) { e.printStackTrace(); return null;//return if the URL is malformed } catch (IOException e) { e.printStackTrace(); return null;//if failed to open a connection } catch (JSONException e) { e.printStackTrace(); return null;//invalid JSON response } return jsonResponse; }
From source file:TargetsAPI.java
/** * Send the POST request to the Wikitude Cloud Targets API. * //w ww .j av a 2s . co m * <b>Remark</b>: We are not using any external libraries for sending HTTP * requests, to be as independent as possible. Libraries like Apache * HttpComponents (included in Android already) make it a lot easier to * interact with HTTP connections. * * @param body * The JSON body that is sent in the request. * @return The response from the server, in JSON format * * @throws IOException * when the server cannot serve the request for any reason, or * anything went wrong during the communication between client * and server. * */ private String sendRequest(String body) throws IOException { BufferedReader reader = null; OutputStreamWriter writer = null; try { // create the URL object from the endpoint URL url = new URL(API_ENDPOINT); // open the connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // use POST and configure the connection connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); // set the request headers connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("X-Api-Token", apiToken); connection.setRequestProperty("X-Version", "" + apiVersion); connection.setRequestProperty("Content-Length", String.valueOf(body.length())); // construct the writer and write request writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(body); writer.flush(); // listen on the server response reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // construct the server response and return StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null;) { sb.append(line); } // return the result return sb.toString(); } catch (MalformedURLException e) { // the URL we specified as endpoint was not valid System.err.println("The URL " + API_ENDPOINT + " is not a valid URL"); e.printStackTrace(); return null; } catch (ProtocolException e) { // this should not happen, it means that we specified a wrong // protocol System.err.println("The HTTP method is not valid. Please check if you specified POST."); e.printStackTrace(); return null; } finally { // close the reader and writer try { writer.close(); } catch (Exception e) { // intentionally left blank } try { reader.close(); } catch (Exception e) { // intentionally left blank } } }