List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java
public HttpResponse execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try {/*from w w w . j a va 2s. com*/ if (parameters != null && !parameters.isEmpty()) { final StringBuilder buf = new StringBuilder(256); if (HTTP_GET.equals(method) || HTTP_HEAD.equals(method)) { buf.append('?'); } int paramIdx = 0; for (final Map.Entry<String, String> e : parameters.entrySet()) { if (paramIdx != 0) { buf.append("&"); } final String name = e.getKey(); final String value = e.getValue(); buf.append(URLEncoder.encode(name, CONTENT_CHARSET)).append("=") .append(URLEncoder.encode(value, CONTENT_CHARSET)); ++paramIdx; } if (!contentSet && (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method))) { try { content = buf.toString().getBytes(CONTENT_CHARSET); } catch (UnsupportedEncodingException e) { // Unlikely to happen. throw new HttpClientException("Encoding error", e); } } else { uri += buf; } } conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setConnectTimeout(hc.getConnectTimeout()); conn.setReadTimeout(hc.getReadTimeout()); conn.setAllowUserInteraction(false); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setUseCaches(false); conn.setDoInput(true); if (headers != null && !headers.isEmpty()) { for (final Map.Entry<String, List<String>> e : headers.entrySet()) { final List<String> values = e.getValue(); if (values != null) { final String name = e.getKey(); for (final String value : values) { conn.addRequestProperty(name, value); } } } } if (cookies != null && !cookies.isEmpty() || hc.getInMemoryCookies() != null && !hc.getInMemoryCookies().isEmpty()) { final StringBuilder cookieHeaderValue = new StringBuilder(256); prepareCookieHeader(cookies, cookieHeaderValue); prepareCookieHeader(hc.getInMemoryCookies(), cookieHeaderValue); conn.setRequestProperty("Cookie", cookieHeaderValue.toString()); } final String userAgent = hc.getUserAgent(); if (userAgent != null) { conn.setRequestProperty("User-Agent", userAgent); } conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Location", uri); conn.setRequestProperty("Referrer", uri); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) { if (content != null) { conn.setDoOutput(true); if (!contentSet) { conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + CONTENT_CHARSET); } else if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } conn.setFixedLengthStreamingMode(content.length); final OutputStream out = conn.getOutputStream(); out.write(content); out.flush(); } else { conn.setFixedLengthStreamingMode(0); } } for (final HttpRequestHandler connHandler : reqHandlers) { try { connHandler.onRequest(conn); } catch (HttpClientException e) { throw e; } catch (Exception e) { throw new HttpClientException("Failed to prepare request to " + uri, e); } } conn.connect(); final int statusCode = conn.getResponseCode(); if (statusCode == -1) { throw new HttpClientException("Invalid response from " + uri); } if (!expectedStatusCodes.isEmpty() && !expectedStatusCodes.contains(statusCode)) { throw new HttpClientException( "Expected status code " + expectedStatusCodes + ", got " + statusCode); } else if (expectedStatusCodes.isEmpty() && statusCode / 100 != 2) { throw new HttpClientException("Expected status code 2xx, got " + statusCode); } final Map<String, List<String>> headerFields = conn.getHeaderFields(); final Map<String, String> inMemoryCookies = hc.getInMemoryCookies(); if (headerFields != null) { final List<String> newCookies = headerFields.get("Set-Cookie"); if (newCookies != null) { for (final String newCookie : newCookies) { final String rawCookie = newCookie.split(";", 2)[0]; final int i = rawCookie.indexOf('='); final String name = rawCookie.substring(0, i); final String value = rawCookie.substring(i + 1); inMemoryCookies.put(name, value); } } } if (isStatusCodeError(statusCode)) { // Got an error: cannot read input. payloadStream = new UncloseableInputStream(getErrorStream(conn)); } else { payloadStream = new UncloseableInputStream(getInputStream(conn)); } final HttpResponse resp = new HttpResponse(statusCode, payloadStream, headerFields == null ? NO_HEADERS : headerFields, inMemoryCookies); if (handler != null) { try { handler.onResponse(resp); } catch (HttpClientException e) { e.printStackTrace(); throw e; } catch (Exception e) { throw new HttpClientException("Error in response handler", e); } } else { final File temp = File.createTempFile("httpclient-req-", ".cache", hc.getContext().getCacheDir()); resp.preload(temp); temp.delete(); } return resp; } catch (SocketTimeoutException e) { if (handler != null) { try { handler.onTimeout(); return null; } catch (HttpClientException e2) { throw e2; } catch (Exception e2) { throw new HttpClientException("Error in response handler", e2); } } else { throw new HttpClientException("Response timeout from " + uri, e); } } catch (IOException e) { throw new HttpClientException("Connection failed to " + uri, e); } finally { if (conn != null) { if (payloadStream != null) { // Fully read Http response: // http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-keepalive.html try { while (payloadStream.read(buffer) != -1) { ; } } catch (IOException ignore) { } payloadStream.forceClose(); } conn.disconnect(); } } }
From source file:com.facebook.Request.java
final static void serializeToUrlConnection(RequestBatch requests, HttpURLConnection connection) throws IOException, JSONException { Logger logger = new Logger(LoggingBehavior.REQUESTS, "Request"); int numRequests = requests.size(); boolean shouldUseGzip = isGzipCompressible(requests); HttpMethod connectionHttpMethod = (numRequests == 1) ? requests.get(0).httpMethod : HttpMethod.POST; connection.setRequestMethod(connectionHttpMethod.name()); setConnectionContentType(connection, shouldUseGzip); URL url = connection.getURL(); logger.append("Request:\n"); logger.appendKeyValue("Id", requests.getId()); logger.appendKeyValue("URL", url); logger.appendKeyValue("Method", connection.getRequestMethod()); logger.appendKeyValue("User-Agent", connection.getRequestProperty("User-Agent")); logger.appendKeyValue("Content-Type", connection.getRequestProperty("Content-Type")); connection.setConnectTimeout(requests.getTimeout()); connection.setReadTimeout(requests.getTimeout()); // If we have a single non-POST request, don't try to serialize anything or HttpURLConnection will // turn it into a POST. boolean isPost = (connectionHttpMethod == HttpMethod.POST); if (!isPost) { logger.log();//w w w . ja v a 2 s. c om return; } connection.setDoOutput(true); OutputStream outputStream = null; try { outputStream = new BufferedOutputStream(connection.getOutputStream()); if (shouldUseGzip) { outputStream = new GZIPOutputStream(outputStream); } if (hasOnProgressCallbacks(requests)) { ProgressNoopOutputStream countingStream = null; countingStream = new ProgressNoopOutputStream(requests.getCallbackHandler()); processRequest(requests, null, numRequests, url, countingStream, shouldUseGzip); int max = countingStream.getMaxProgress(); Map<Request, RequestProgress> progressMap = countingStream.getProgressMap(); outputStream = new ProgressOutputStream(outputStream, requests, progressMap, max); } processRequest(requests, logger, numRequests, url, outputStream, shouldUseGzip); } finally { if (outputStream != null) { outputStream.close(); } } logger.log(); }
From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
public boolean resumeImages(String msgSubject) { File file = null;//from www. j ava 2 s .c om long fileLength; try { String filename = "", num = ""; URL url = new URL(imageUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); num = getNumber(msgSubject); filename = getTimestamp(msgSubject); file = new File(fileDir + "/" + getNumber(msgSubject) + "/Recieved", filename); if (!file.exists()) { file.createNewFile(); } FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = connection.getInputStream(); int totalSize = connection.getContentLength(); Long downloadedSize = (long) 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize); } fileOutput.close(); Log.d("downloadedSize", downloadedSize + " @"); if (downloadedSize == totalSize) { downloadedimageuri = file.getAbsolutePath(); return true; } if (file.exists()) { connection.setAllowUserInteraction(true); connection.setRequestProperty("Range", "bytes=" + file.length() + "-"); } connection.setConnectTimeout(14000); connection.setReadTimeout(20000); connection.connect(); if (connection.getResponseCode() / 100 != 2) throw new Exception("Invalid response code!"); else { String connectionField = connection.getHeaderField("content-range"); if (connectionField != null) { String[] connectionRanges = connectionField.substring("bytes=".length()).split("-"); downloadedSize = Long.valueOf(connectionRanges[0]); } if (connectionField == null && file.exists()) file.delete(); fileLength = connection.getContentLength() + downloadedSize; BufferedInputStream input = new BufferedInputStream(connection.getInputStream()); RandomAccessFile output = new RandomAccessFile(file, "rw"); output.seek(downloadedSize); byte data[] = new byte[1024]; int count = 0; int __progress = 0; while ((count = input.read(data, 0, 1024)) != -1 && __progress != 100) { downloadedSize += count; output.write(data, 0, count); __progress = (int) ((downloadedSize * 100) / fileLength); } output.close(); input.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return false; }
From source file:com.canappi.connector.yp.yhere.GameView.java
public ArrayList<Element> searchGamesByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {/*from w ww . j a v a2 s. c om*/ URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=games&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=games&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }
From source file:com.canappi.connector.yp.yhere.BakeryView.java
public ArrayList<Element> searchBakeriesByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {//from w w w . jav a 2 s . c o m URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=bakery&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=bakery&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }
From source file:com.canappi.connector.yp.yhere.GroceryView.java
public ArrayList<Element> searchGroceryStoresByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {//from w w w. j a va 2s . c o m URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=grocery&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=grocery&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }
From source file:com.canappi.connector.yp.yhere.TheaterView.java
public ArrayList<Element> searchTeathersByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {/*from w ww . ja v a 2s . com*/ URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=theater&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=theater&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }
From source file:com.canappi.connector.yp.yhere.LubeView.java
public ArrayList<Element> searchOilChangeByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {// w w w. j av a 2 s .c o m URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=oil+change&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=oil+change&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }
From source file:com.canappi.connector.yp.yhere.RestaurantView.java
public ArrayList<Element> searchRestaurantsByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {/*from w ww . j a va2 s .co m*/ URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=restaurant&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=restaurant&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }
From source file:com.canappi.connector.yp.yhere.GasStationView.java
public ArrayList<Element> searchGasStationByZip(HashMap<String, String> requestParameters) { ArrayList<Element> data = new ArrayList<Element>(); System.setProperty("http.keepAlive", "false"); System.setProperty("javax.net.debug", "all"); // _FakeX509TrustManager.allowAllSSL(); //Protocol::: HTTP GET StringBuffer query = new StringBuffer(); HttpURLConnection connection = null; try {/*from w ww . j a va 2 s . co m*/ URL url; if (requestParameters != null) { String key; query.append( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=gas+station&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); query.append("&"); key = "searchloc"; String searchlocValue = requestParameters.get(key); String searchlocDefaultValue = retrieveFromUserDefaultsFor(key); if (searchlocValue.length() > 0) { query.append("" + key + "=" + requestParameters.get(key)); } else { //try to find the value in the user defaults if (searchlocDefaultValue != null) { query.append("" + key + "=" + retrieveFromUserDefaultsFor(key)); } } url = new URL(query.toString()); } else { url = new URL( "http://api2.yp.com/listings/v1/search?format=xml&sort=distance&radius=5&term=gas+station&listingcount=10&key=5d0b448ba491c2dff5a36040a125df0a"); } connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); connection.setUseCaches(false); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int rc = connection.getResponseCode(); Log.i("Response code", String.valueOf(rc)); InputStream is; if (rc <= 400) { is = connection.getInputStream(); } else { /* error from server */ is = connection.getErrorStream(); } //XML ResultSet try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource isrc = new InputSource(); isrc.setByteStream(is); Document doc = db.parse(isrc); NodeList nodes = doc.getElementsByTagName("searchListings"); if (nodes.getLength() > 0) { Element list = (Element) nodes.item(0); NodeList l = list.getChildNodes(); for (int i = 0; i < l.getLength(); i++) { Node n = l.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element row = (Element) l.item(i); data.add(row); } } } } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return data; }