List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:cm.aptoide.pt.LatestLikesComments.java
public Cursor getLikes() { endPointLikes = String.format(endPointLikes, repoName); MatrixCursor cursor = new MatrixCursor(new String[] { "_id", "apkid", "name", "like", "username" }); try {// ww w .ja v a 2s .c o m HttpURLConnection connection = (HttpURLConnection) new URL(endPointLikes).openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); JSONObject respJSON = new JSONObject(sb.toString()); JSONArray array = respJSON.getJSONArray("listing"); for (int i = 0; i != array.length(); i++) { String apkid = ((JSONObject) array.get(i)).getString("apkid"); String name = ((JSONObject) array.get(i)).getString("name"); String like = ((JSONObject) array.get(i)).getString("like"); String username = ((JSONObject) array.get(i)).getString("username"); if (username.equals("NOT_SIGNED_UP")) { username = ""; } cursor.newRow().add(i).add(apkid).add(name).add(like).add(username); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return cursor; }
From source file:com.micro.utils.F.java
/** * ????./*from ww w.j av a 2s. c o m*/ * @param url ? * @return ?? */ public static String getRealFileNameFromUrl(String url) { String name = null; try { if (TextUtils.isEmpty(url)) { return name; } URL mUrl = new URL(url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", ""); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { for (int i = 0;; i++) { String mine = mHttpURLConnection.getHeaderField(i); if (mine == null) { break; } if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase()); if (m.find()) return m.group(1).replace("\"", ""); } } } } catch (Exception e) { e.printStackTrace(); L.E("???"); } return name; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Connects to the server, authenticates the provided username and * password.//from w w w . j ava 2s . c om * * @param username The user's username * @param password The user's password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String accessKey, String base_url) { String token = null; String hash = null; authenticate_log_text = "authenticate()\n"; AUTH_URI = base_url + "/webservice.php"; authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username=" + username + "\n"; Log.d(TAG, "AUTH_URI : "); Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); // =========== get challenge token ============================== ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); try { URL url; // HTTP GET REQUEST url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setUseCaches(false); // for some site that redirects based on user agent con.setInstanceFollowRedirects(true); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15"); con.setAllowUserInteraction(false); int timeout = 20000; con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n"; switch (status) { case 200: case 201: case 302: BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "body : " + sb.toString(); if (status == 302) { authenticate_log_text = sb.toString(); return null; } JSONObject result = new JSONObject(sb.toString()); Log.d(TAG, result.getString("result")); JSONObject data = new JSONObject(result.getString("result")); token = data.getString("token"); break; case 401: Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "Server auth error"; return null; default: Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "connection status code :" + status; return null; } } catch (ClientProtocolException e) { Log.i(TAG, "getchallenge:http protocol error"); Log.e(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n"; return null; } catch (IOException e) { Log.e(TAG, "getchallenge: IO Exception"); Log.e(TAG, e.getMessage()); Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n"; return null; } catch (JSONException e) { Log.i(TAG, "json exception"); authenticate_log_text = authenticate_log_text + "JSon exception\n"; // TODO Auto-generated catch block e.printStackTrace(); return null; } // ================= login ================== try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(token.getBytes()); m.update(accessKey.getBytes()); hash = new BigInteger(1, m.digest()).toString(16); Log.i(TAG, "hash"); Log.i(TAG, hash); } catch (NoSuchAlgorithmException e) { authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n"; e.printStackTrace(); } try { String charset; charset = "utf-8"; String query = String.format("operation=login&username=%s&accessKey=%s", URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset)); authenticate_log_text = authenticate_log_text + "login()\n"; URLConnection connection = new URL(AUTH_URI).openConnection(); connection.setDoOutput(true); // Triggers POST. int timeout = 20000; connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); connection.setUseCaches(false); OutputStream output = connection.getOutputStream(); try { output.write(query.getBytes(charset)); } finally { try { output.close(); } catch (IOException logOrIgnore) { } } Log.d(TAG, "Query written"); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message post body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n"; JSONObject result = new JSONObject(sb.toString()); String success = result.getString("success"); Log.i(TAG, success); if (success == "true") { Log.i(TAG, result.getString("result")); Log.i(TAG, "sucesssfully logged in is"); JSONObject data = new JSONObject(result.getString("result")); sessionName = data.getString("sessionName"); Log.i(TAG, sessionName); authenticate_log_text = authenticate_log_text + "successfully logged in\n"; return token; } else { // success is false, retrieve error JSONObject data = new JSONObject(result.getString("error")); authenticate_log_text = "can not login :\n" + data.toString(); return null; } //token = data.getString("token"); //Log.i(TAG,token); } catch (ClientProtocolException e) { Log.d(TAG, "login: http protocol error"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (IOException e) { Log.d(TAG, "login: IO Exception"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "login: IO Exception \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (JSONException e) { Log.d(TAG, "JSON exception"); // TODO Auto-generated catch block authenticate_log_text = authenticate_log_text + "JSON exception "; authenticate_log_text = authenticate_log_text + e.getMessage(); e.printStackTrace(); } return null; // ======================================================================== }
From source file:com.snda.mymarket.providers.downloads.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * @param url/*ww w. j a va 2s. c o m*/ * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, HttpUriRequest request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = TIMEOUT_MSECONDES; connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); connection.setDoInput(true); return connection; }
From source file:eu.codeplumbers.cosi.api.tasks.UnregisterDeviceTask.java
@Override protected String doInBackground(Void... voids) { URL urlO = null;//from www . j a v a 2 s . c om try { urlO = new URL(url + Device.registeredDevice().getLogin()); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(false); conn.setDoInput(true); conn.setRequestMethod("DELETE"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); if (result == "") { Device.registeredDevice().delete(); new Delete().from(Call.class).execute(); new Delete().from(Note.class).execute(); new Delete().from(Sms.class).execute(); new Delete().from(Place.class).execute(); new Delete().from(File.class).execute(); errorMessage = ""; } else { errorMessage = result; } in.close(); conn.disconnect(); } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } return errorMessage; }
From source file:org.fashiontec.bodyapps.sync.Sync.java
/** * Downloads a file from given URL./* ww w . ja v a2 s.com*/ * * @param url * @param file * @return */ public int download(String url, String file) { try { URL u = new URL(url); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setConnectTimeout(2000); c.setRequestProperty("Accept", "application/vnd.valentina.hdf"); c.connect(); FileOutputStream f = new FileOutputStream(new File(file)); InputStream in = c.getInputStream(); //download code byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = in.read(buffer)) > 0) { f.write(buffer, 0, len1); } f.close(); } catch (Exception e) { Log.e(TAG, e.getMessage()); return -1; } return 1; }
From source file:de.fu_berlin.inf.dpp.netbeans.feedback.FileSubmitter.java
/** * Tries to upload the given file to the given HTTP server (via POST * method).//from w ww . j ava 2s . c o m * * @param file * the file to upload * @param url * the URL of the server, that is supposed to handle the file * @param monitor * a monitor to report progress to * @throws IOException * if an I/O error occurs * */ public static void uploadFile(final File file, final String url, IProgressMonitor monitor) throws IOException { final String CRLF = "\r\n"; final String doubleDash = "--"; final String boundary = generateBoundary(); HttpURLConnection connection = null; OutputStream urlConnectionOut = null; FileInputStream fileIn = null; if (monitor == null) monitor = new NullProgressMonitor(); int contentLength = (int) file.length(); if (contentLength == 0) { log.warn("file size of file " + file.getAbsolutePath() + " is 0 or the file does not exist"); return; } monitor.beginTask("Uploading file " + file.getName(), contentLength); try { URL connectionURL = new URL(url); if (!"http".equals(connectionURL.getProtocol())) throw new IOException("only HTTP protocol is supported"); connection = (HttpURLConnection) connectionURL.openConnection(); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setReadTimeout(TIMEOUT); connection.setConnectTimeout(TIMEOUT); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); String contentDispositionLine = "Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"" + CRLF; String contentTypeLine = "Content-Type: application/octet-stream; charset=ISO-8859-1" + CRLF; String contentTransferEncoding = "Content-Transfer-Encoding: binary" + CRLF; contentLength += 2 * boundary.length() + contentDispositionLine.length() + contentTypeLine.length() + contentTransferEncoding.length() + 4 * CRLF.length() + 3 * doubleDash.length(); connection.setFixedLengthStreamingMode(contentLength); connection.connect(); urlConnectionOut = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(urlConnectionOut, "US-ASCII"), true); writer.append(doubleDash).append(boundary).append(CRLF); writer.append(contentDispositionLine); writer.append(contentTypeLine); writer.append(contentTransferEncoding); writer.append(CRLF); writer.flush(); fileIn = new FileInputStream(file); byte[] buffer = new byte[8192]; for (int read = 0; (read = fileIn.read(buffer)) > 0;) { if (monitor.isCanceled()) return; urlConnectionOut.write(buffer, 0, read); monitor.worked(read); } urlConnectionOut.flush(); writer.append(CRLF); writer.append(doubleDash).append(boundary).append(doubleDash).append(CRLF); writer.close(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { log.debug("uploaded file " + file.getAbsolutePath() + " to " + connectionURL.getHost()); return; } throw new IOException("failed to upload file " + file.getAbsolutePath() + connectionURL.getHost() + " [" + connection.getResponseMessage() + "]"); } finally { IOUtils.closeQuietly(fileIn); IOUtils.closeQuietly(urlConnectionOut); if (connection != null) connection.disconnect(); monitor.done(); } }
From source file:mobi.espier.lgc.data.UploadHelper.java
private String doHttpPostAndGetResponse(String url, byte[] data) { if (TextUtils.isEmpty(url) || data == null || data.length < 1) { return null; }//ww w .j av a 2s .co m String response = null; try { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); int mResponseCode = conn.getResponseCode(); if (mResponseCode == 200) { response = getHttpResponse(conn); } conn.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return response; }
From source file:org.peterbaldwin.vlcremote.sweep.Worker.java
@Override public void run() { // Note: InetAddress#isReachable(int) always returns false for Windows // hosts because applications do not have permission to perform ICMP // echo requests. for (;;) {/* w w w.j a va 2s .c o m*/ byte[] ipAddress = mManager.pollIpAddress(); if (ipAddress == null) { break; } try { InetAddress address = InetAddress.getByAddress(ipAddress); String hostAddress = address.getHostAddress(); URL url = createUrl("http", hostAddress, mPort, mPath); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1000); try { int responseCode = connection.getResponseCode(); String responseMessage = connection.getResponseMessage(); InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? connection.getInputStream() : connection.getErrorStream(); if (inputStream != null) { try { int length = connection.getContentLength(); InputStreamEntity entity = new InputStreamEntity(inputStream, length); entity.setContentType(connection.getContentType()); // Copy the entire response body into memory // before the HTTP connection is closed: String body = EntityUtils.toString(entity); ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1); String hostname = address.getHostName(); StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage); HttpResponse response = new BasicHttpResponse(statusLine); response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort); response.setEntity(new StringEntity(body)); mCallback.onReachable(ipAddress, response); } finally { inputStream.close(); } } else { Log.w(TAG, "InputStream is null"); } } finally { connection.disconnect(); } } catch (IOException e) { mCallback.onUnreachable(ipAddress, e); } } }
From source file:uk.ac.manchester.cs.owl.semspreadsheets.repository.bioportal.BioPortalRepositoryAccessor.java
public Collection<RepositoryItem> getOntologies() { final Collection<RepositoryItem> items = new ArrayList<RepositoryItem>(); URL url = null;//from w w w . j av a2 s .c o m try { url = new URL( BioPortalRepository.ONTOLOGY_LIST + "?format=json&apikey=" + BioPortalRepository.readAPIKey()); logger.debug("Contacting BioPortal REST API at: " + url.toExternalForm()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(CONNECT_TIMEOUT); int responseCode = connection.getResponseCode(); logger.info("BioPortal http response: " + responseCode); if (responseCode == 400 || responseCode == 403) { throw new BioPortalAccessDeniedException(); } ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(connection.getInputStream()); for (final JsonNode item : node) { String name = item.get("name").asText(); String id = item.get("acronym").asText(); BioPortalRepositoryItem repositoryItem = new BioPortalRepositoryItem(id, name, this); if (repositoryItem.isCompatible()) { items.add(repositoryItem); } } if (SAVE_PROPERTIES_CACHE) { BioPortalCache.getInstance().dumpStoredProperties(); } } catch (UnknownHostException e) { ErrorHandler.getErrorHandler().handleError(e); } catch (MalformedURLException e) { logger.error("Error with URL for BioPortal rest API", e); } catch (SocketTimeoutException e) { logger.error("Timeout connecting to BioPortal", e); ErrorHandler.getErrorHandler().handleError(e); } catch (IOException e) { logger.error("Error communiciating with BioPortal rest API", e); } catch (BioPortalAccessDeniedException e) { ErrorHandler.getErrorHandler().handleError(e); } return items; }