List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java
/** * * @param httpParam/*from w w w . ja va2 s . co m*/ * @return */ public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) { String url = httpParam.getUrl(); Map<String, Object> parameters = httpParam.getParameters(); String sMethod = httpParam.getMethod(); String charSet = httpParam.getCharSet(); boolean sslVerify = httpParam.isSslVerify(); int maxResultSize = httpParam.getMaxResultSize(); Map<String, Object> headers = httpParam.getHeaders(); int readTimeout = httpParam.getReadTimeout(); int connectTimeout = httpParam.getConnectTimeout(); boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess(); boolean hostnameVerify = httpParam.isHostnameVerify(); TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore(); ClientKeyStore clientKeyStore = httpParam.getClientKeyStore(); if (url == null || url.trim().length() == 0) { throw new IllegalArgumentException("invalid url : " + url); } if (maxResultSize <= 0) { throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize); } Charset.forName(charSet); HttpURLConnection urlConn = null; URL destURL = null; String baseUrl = url.trim(); if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) { baseUrl = HTTP_PREFIX + baseUrl; } String method = null; if (sMethod != null) { method = sMethod.toUpperCase(); } if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) { throw new IllegalArgumentException("invalid http method : " + method); } int index = baseUrl.indexOf("?"); if (index > 0) { baseUrl = urlEncode(baseUrl, charSet); } else if (index == 0) { throw new IllegalArgumentException("invalid url : " + url); } String queryString = mapToQueryString(parameters, charSet); String targetUrl = ""; if (method.equals(HTTP_METHOD_POST)) { targetUrl = baseUrl; } else { if (index > 0) { targetUrl = baseUrl + "&" + queryString; } else { targetUrl = baseUrl + "?" + queryString; } } try { destURL = new URL(targetUrl); urlConn = (HttpURLConnection) destURL.openConnection(); setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore); boolean hasContentType = false; boolean hasUserAgent = false; for (String key : headers.keySet()) { if ("Content-Type".equalsIgnoreCase(key)) { hasContentType = true; } if ("user-agent".equalsIgnoreCase(key)) { hasUserAgent = true; } } if (!hasContentType) { headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet); } if (!hasUserAgent) { headers.put("user-agent", "PlatSystem"); } if (headers != null && !headers.isEmpty()) { for (Entry<String, Object> entry : headers.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); List<String> values = makeStringList(value); for (String v : values) { urlConn.addRequestProperty(key, v); } } } urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setRequestMethod(method); urlConn.setConnectTimeout(connectTimeout); urlConn.setReadTimeout(readTimeout); if (method.equals(HTTP_METHOD_POST)) { String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString; if (postData != null && postData.trim().length() > 0) { OutputStream os = urlConn.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os, charSet); osw.write(postData); osw.flush(); osw.close(); } } int responseCode = urlConn.getResponseCode(); Map<String, List<String>> responseHeaders = urlConn.getHeaderFields(); String contentType = urlConn.getContentType(); SimpleHttpResult result = new SimpleHttpResult(responseCode); result.setHeaders(responseHeaders); result.setContentType(contentType); if (responseCode != 200 && ignoreContentIfUnsuccess) { return result; } InputStream is = urlConn.getInputStream(); byte[] temp = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int readBytes = is.read(temp); while (readBytes > 0) { baos.write(temp, 0, readBytes); readBytes = is.read(temp); } String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet); baos.close(); result.setContent(resultString); return result; } catch (Exception e) { logger.warn("connection error : " + e.getMessage()); return new SimpleHttpResult(e); } finally { if (urlConn != null) { urlConn.disconnect(); } } }
From source file:org.runnerup.export.RuntasticUploader.java
@Override public Status connect() { Exception ex = null;//from www. j av a 2 s. c o m HttpURLConnection conn = null; formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } System.out.println("userId: " + userId + ", authToken: " + authToken); if (userId != null && authToken != null) { return Status.OK; } cookies.clear(); try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); addRequestHeaders(conn); { // int responseCode = conn.getResponseCode(); // String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); authToken = formValues.get("authenticity_token"); } conn.disconnect(); if (authToken == null) return Status.ERROR; /** * Then login using a post */ FormValues kv = new FormValues(); kv.put("user[email]", username); kv.put("user[password]", password); kv.put("authenticity-token", authToken); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); addRequestHeaders(conn); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String url2 = null; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); // int responseCode = conn.getResponseCode(); // String amsg = conn.getResponseMessage(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject ret = parse(in); if (ret != null && ret.has("success") && ret.getBoolean("success")) { Matcher matcher = Patterns.WEB_URL.matcher(ret.getString("update")); while (matcher.find()) { String tmp = matcher.group(); final String users = "/users/"; if (tmp.contains(users)) { int i = tmp.indexOf(users) + users.length(); int i2 = tmp.indexOf('/', i); if (i2 > 0) url2 = tmp.substring(0, i2); else url2 = tmp; if (url2 != null) break; } } } System.out.println("found url2: " + url2); conn.disconnect(); } if (url2 == null) { return s; } { url2 = url2 + "?authenticity_token=" + URLEncode(authToken); conn = (HttpURLConnection) new URL(url2).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Host", "www.runtastic.com"); conn.addRequestProperty("Accept", "application/json"); InputStream in = new BufferedInputStream(conn.getInputStream()); getCookies(conn); JSONObject ret = parse(in); userId = ret.getJSONObject("user").getInt("id"); conn.disconnect(); } if (userId != null && authToken != null) { return Status.OK; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.runnerup.export.RuntasticSynchronizer.java
@Override public Status connect() { Exception ex = null;//from w ww. j a va2 s . c om HttpURLConnection conn = null; formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } Log.i(getName(), "userId: " + userId + ", authToken: " + authToken); if (userId != null && authToken != null) { return Status.OK; } cookies.clear(); try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); addRequestHeaders(conn); { // int responseCode = conn.getResponseCode(); // String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); authToken = formValues.get("authenticity_token"); } conn.disconnect(); if (authToken == null) return Status.ERROR; /** * Then login using a post */ FormValues kv = new FormValues(); kv.put("user[email]", username); kv.put("user[password]", password); kv.put("authenticity-token", authToken); kv.put("grant_type", "password"); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); addRequestHeaders(conn); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String url2 = null; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); // int responseCode = conn.getResponseCode(); // String amsg = conn.getResponseMessage(); getCookies(conn); InputStream in = new BufferedInputStream(conn.getInputStream()); JSONObject ret = SyncHelper.parse(in); if (ret != null && ret.has("success") && ret.getBoolean("success")) { Matcher matcher = Patterns.WEB_URL.matcher(ret.getString("update")); while (matcher.find()) { String tmp = matcher.group(); final String users = "/users/"; if (tmp.contains(users)) { int i = tmp.indexOf(users) + users.length(); int i2 = tmp.indexOf('/', i); if (i2 > 0) url2 = tmp.substring(0, i2); else url2 = tmp; if (url2 != null) break; } } } Log.i(getName(), "found url2: " + url2); conn.disconnect(); } if (url2 == null) { return s; } { url2 = url2 + "?authenticity_token=" + SyncHelper.URLEncode(authToken); conn = (HttpURLConnection) new URL(url2).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(RequestMethod.GET.name()); conn.setRequestProperty("Host", "www.runtastic.com"); conn.addRequestProperty("Accept", "application/json"); InputStream in = new BufferedInputStream(conn.getInputStream()); getCookies(conn); JSONObject ret = SyncHelper.parse(in); userId = ret.getJSONObject("user").getInt("id"); conn.disconnect(); } if (userId != null && authToken != null) { return Status.OK; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } catch (JSONException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.photon.phresco.framework.rest.api.CIService.java
private JSONObject getResponsePostMethod(String restUrl, String credentials) throws PhrescoException { JSONObject object = new JSONObject(); try {//from w ww . j a v a 2s . c om URL url = new URL(restUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(POST); urlConnection.addRequestProperty("Accept", "application/json"); urlConnection.addRequestProperty(AUTHORIZATION, BASIC_SPACE + credentials); urlConnection.addRequestProperty(CONTENT_TYPE, "application/x-www-form-urlencoded"); int responseCode = urlConnection.getResponseCode(); String message = responseCode == 200 ? "Bamboo build started" : "Bamboo build not Started"; StringBuilder sb = new StringBuilder(); if (responseCode == 200) { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } } object.put("code", responseCode); object.put("message", message); object.put("result", sb.toString()); } catch (MalformedURLException e) { throw new PhrescoException(e); } catch (IOException e) { throw new PhrescoException(e); } return object; }
From source file:org.runnerup.export.FunBeatUploader.java
@Override public Status connect() { Exception ex = null;//from w ww . j a va 2 s .c o m HttpURLConnection conn = null; cookies.clear(); formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (loginID == null || loginSecretHashed == null) { if (!validateAndCreateSecrets(username, password)) return s; } try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); System.out.println("FunBeat.START_URL => code: " + responseCode + "(" + amsg + "), cookies: " + cookies.size() + ", values: " + formValues.size()); } conn.disconnect(); /** * Then login using a post */ FormValues kv = new FormValues(); String viewKey = findName(formValues.keySet(), "VIEWSTATE"); String eventKey = findName(formValues.keySet(), "EVENTVALIDATION"); String userKey = findName(formValues.keySet(), "Username"); String passKey = findName(formValues.keySet(), "Password"); String loginKey = findName(formValues.keySet(), "LoginButton"); kv.put(viewKey, formValues.get(viewKey)); kv.put(eventKey, formValues.get(eventKey)); kv.put(userKey, username); kv.put(passKey, password); kv.put(loginKey, "Logga in"); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); boolean ok = false; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode == 302) { String redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("GET"); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } else if (responseCode != 200) { System.err.println("FunBeatUploader::connect() - got " + responseCode + ", msg: " + amsg); } String html = getFormValues(conn); ok = html.indexOf("Logga ut") > 0; conn.disconnect(); } if (ok) { return Uploader.Status.OK; } else { return s; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:org.runnerup.export.FunBeatSynchronizer.java
@Override public Status connect() { Exception ex = null;/*from w w w . ja va 2s . c om*/ HttpURLConnection conn = null; cookies.clear(); formValues.clear(); Status s = Status.NEED_AUTH; s.authMethod = AuthMethod.USER_PASS; if (username == null || password == null) { return s; } if (loginID == null || loginSecretHashed == null) { if (!validateAndCreateSecrets(username, password)) return s; } try { /** * connect to START_URL to get cookies/formValues */ conn = (HttpURLConnection) new URL(START_URL).openConnection(); conn.setInstanceFollowRedirects(false); { int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); getFormValues(conn); Log.i(getName(), "FunBeat.START_URL => code: " + responseCode + "(" + amsg + "), cookies: " + cookies.size() + ", values: " + formValues.size()); } conn.disconnect(); /** * Then login using a post */ FormValues kv = new FormValues(); String viewKey = SyncHelper.findName(formValues.keySet(), "VIEWSTATE"); String eventKey = SyncHelper.findName(formValues.keySet(), "EVENTVALIDATION"); String userKey = SyncHelper.findName(formValues.keySet(), "Username"); String passKey = SyncHelper.findName(formValues.keySet(), "Password"); String loginKey = SyncHelper.findName(formValues.keySet(), "LoginButton"); kv.put(viewKey, formValues.get(viewKey)); kv.put(eventKey, formValues.get(eventKey)); kv.put(userKey, username); kv.put(passKey, password); kv.put(loginKey, "Logga in"); conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection(); conn.setInstanceFollowRedirects(false); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); addCookies(conn); boolean ok = false; { OutputStream wr = new BufferedOutputStream(conn.getOutputStream()); kv.write(wr); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); getCookies(conn); if (responseCode == HttpStatus.SC_MOVED_TEMPORARILY) { String redirect = conn.getHeaderField("Location"); conn.disconnect(); conn = (HttpURLConnection) new URL(BASE_URL + redirect).openConnection(); conn.setInstanceFollowRedirects(false); conn.setRequestMethod(RequestMethod.GET.name()); addCookies(conn); responseCode = conn.getResponseCode(); amsg = conn.getResponseMessage(); getCookies(conn); } else if (responseCode != HttpStatus.SC_OK) { Log.e(getName(), "FunBeatSynchronizer::connect() - got " + responseCode + ", msg: " + amsg); } String html = getFormValues(conn); ok = html.indexOf("Logga ut") > 0; conn.disconnect(); } if (ok) { return Synchronizer.Status.OK; } else { return s; } } catch (MalformedURLException e) { ex = e; } catch (IOException e) { ex = e; } if (conn != null) conn.disconnect(); s.ex = ex; if (ex != null) { ex.printStackTrace(); } return s; }
From source file:com.truebanana.http.HTTPRequest.java
/** * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}. * * @return This {@link HTTPRequest}//from w ww.j a va 2 s. com */ public HTTPRequest executeAsync() { Async.executeAsync(new Runnable() { @Override public void run() { HttpURLConnection urlConnection = buildURLConnection(); // Get request body now if there's a provider if (bodyProvider != null) { body = bodyProvider.getRequestBody(); } // Update socket factory as needed if (urlConnection instanceof HttpsURLConnection) { HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection; try { httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore, trustStorePassword, keyStore, keyStorePassword, !verifySSL)); } catch (GeneralSecurityException e) { e.printStackTrace(); onRequestError(HTTPRequestError.SECURITY_EXCEPTION); onRequestTerminated(); return; // Terminate now } catch (IOException e) { e.printStackTrace(); onRequestError(HTTPRequestError.KEYSTORE_INVALID); onRequestTerminated(); return; // Terminate now } if (!verifySSL) { httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier()); log("SSL Verification Disabled", "**********"); } } log("Endpoint", urlConnection.getURL().toString()); Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> pair = (Map.Entry) iterator.next(); urlConnection.addRequestProperty(pair.getKey(), pair.getValue()); log("Request Header", pair.getKey() + ": " + pair.getValue()); } if (multiPartContent != null) { log("Multipart Request Boundary", multiPartContent.getBoundary()); int counter = 1; for (MultiPartContent.Part part : multiPartContent.getParts()) { log("Request Body Part " + counter, "Name: " + part.getName() + "; File Name: " + part.getFileName()); Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> pair = (Map.Entry) it.next(); log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue()); } } } else { log("Request Body", body); } if (mockResponse == null) { // Trigger pre-execute since preparations are complete onPreExecute(); // Write our request body try { if (multiPartContent != null) { multiPartContent.write(urlConnection.getOutputStream()); } else if (body != null) { OutputStream os = urlConnection.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(os); writer.write(body); writer.flush(); writer.close(); os.close(); } } catch (IOException e) { e.printStackTrace(); onRequestError(HTTPRequestError.OTHER); onRequestTerminated(); return; // Terminate now } // Get the response InputStream content; try { content = urlConnection.getInputStream(); onPostExecute(); } catch (SocketTimeoutException e) { // Timeout e.printStackTrace(); onPostExecute(); onRequestError(HTTPRequestError.TIMEOUT); onRequestTerminated(); return; // Terminate now } catch (IOException e) { // All other exceptions e.printStackTrace(); content = urlConnection.getErrorStream(); onPostExecute(); } // Pre-process the response final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content); if (response.isConnectionError()) { onRequestError(HTTPRequestError.OTHER); onRequestTerminated(); return; // Terminate now } // Log response log("Response Message", response.getResponseMessage()); log("Response Content", response.getStringContent()); // Trigger request completed and return the response onRequestCompleted(response); // Terminate the connection urlConnection.disconnect(); onRequestTerminated(); } else { onPreExecute(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } onPostExecute(); log("Response Message", mockResponse.getResponseMessage()); log("Response Content", mockResponse.getStringContent()); onRequestCompleted(mockResponse); urlConnection.disconnect(); onRequestTerminated(); } } }); return this; }
From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java
@Test public void testWrongContentType() throws Exception { // can't use WebClient here because WebClient plays around with the Content-Type // (and makes sure it's syntactically correct) before sending it to the server String endpointAddress = "http://localhost:" + PORT + "/bookstore/unsupportedcontenttype"; URL url = new URL(endpointAddress); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(30000); // 30 seconds tops urlConnection.setConnectTimeout(30000); // 30 second tops urlConnection.addRequestProperty("Content-Type", "MissingSeparator"); urlConnection.setRequestMethod("POST"); assertEquals(415, urlConnection.getResponseCode()); }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
public boolean downloadMojangLauncher() { URL u;/*ww w .j a v a 2s.co m*/ HttpURLConnection connection; Proxy p; InputStream is; FileOutputStream fos; if (new File(config.getInstallDir(), "Minecraft.jar").isFile()) { return true; } log.println("Connecting to Mojang server..."); if (config.getHttpProxy().isEmpty()) { p = Proxy.NO_PROXY; } else { Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == Authenticator.RequestorType.PROXY) { return config.getHttpProxyCredentials(); } else { return super.getPasswordAuthentication(); } } }); p = new Proxy(Proxy.Type.HTTP, new ProxyAddress(config.getHttpProxy(), 3128).getSockaddr()); } try { u = new URL("https://s3.amazonaws.com/Minecraft.Download/launcher/Minecraft.jar"); connection = (HttpURLConnection) u.openConnection(p); connection.addRequestProperty("User-agent", "Minecraft Bootloader"); connection.setUseCaches(false); connection.setDefaultUseCaches(false); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.connect(); log.println("Mojang server returned " + connection.getResponseMessage()); if (connection.getResponseCode() != 200) { connection.disconnect(); return false; } } catch (MalformedURLException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex); return false; } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex); log.println("Connection to Mojang server failed."); return false; } try { is = connection.getInputStream(); fos = new FileOutputStream(new File(config.getInstallDir(), "Minecraft.jar")); log.println("Downloading Minecraft.jar"); byte[] buffer = new byte[4096]; for (int n = is.read(buffer); n > 0; n = is.read(buffer)) { fos.write(buffer, 0, n); } fos.close(); is.close(); connection.disconnect(); log.println("Done."); } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "downloadMojangLauncher", ex); log.println("Faild to save file."); return false; } return true; }