List of usage examples for java.net HttpURLConnection setAllowUserInteraction
public void setAllowUserInteraction(boolean allowuserinteraction)
From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java
/** * * @param httpParam/*from w w w . j av a2s . com*/ * @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:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java
public boolean resumeImages(String msgSubject) { File file = null;/*from w ww . j av a2 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:org.pixmob.httpclient.HttpRequestBuilder.java
public HttpResponse execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try {/*from w w w . j a v a 2 s. c o m*/ 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); } 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); } } // It seems that when writing content starts the connection if (HTTP_POST.equals(method) || HTTP_DELETE.equals(method) || HTTP_PUT.equals(method)) { if (content == null) { noContent(); } 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(); } 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) { 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:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java
public HttpResponse execute() throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try {/*from ww w .j a v a2s. c o m*/ 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.cr_wd.android.network.HttpClient.java
/** * Performs a HTTP GET/POST Request//from w w w .j ava2 s . c o m * * @return id of the request */ protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params, final HttpHandler handler) { if (headers == null) { headers = new HttpHeaders(); } if (params == null) { params = new HttpParams(); } handler.client = this; final int requestId = incrementRequestId(); class HandlerRunnable extends Handler implements Runnable { private final Method method; private String url; private final HttpHeaders headers; private final HttpParams params; private final HttpHandler handler; private HttpResponse response; private boolean canceled = false; private int retries = 0; protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers, final HttpParams params, final HttpHandler handler) { this.method = method; this.url = url; this.headers = headers; this.params = params; this.handler = handler; } @Override public void run() { execute(); } private void execute() { response = new HttpResponse(requestId, method, url); HttpURLConnection conn = null; try { /* append query string for GET requests */ if (method == Method.GET) { if (!params.urlParams.isEmpty()) { url += ('?' + params.getParamString()); } } /* setup headers for POST requests */ if (method == Method.POST) { headers.addHeader("Accept-Charset", requestOptions.encoding); if (params.hasMultipartParams()) { final SimpleMultipart multipart = params.getMultipart(); headers.addHeader("Content-Type", multipart.getContentType()); } else { headers.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + requestOptions.encoding); } } if (canceled) { postCancel(); return; } /* open and configure the connection */ conn = (HttpURLConnection) new URL(url).openConnection(); postStart(); if (method == Method.GET) { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); } else if (method == Method.POST) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); } conn.setAllowUserInteraction(false); conn.setReadTimeout(requestOptions.readTimeout); conn.setConnectTimeout(requestOptions.connectTimeout); /* add headers to the connection */ for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) { for (final String value : entry.getValue()) { conn.addRequestProperty(entry.getKey(), value); } } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.requestProperties = conn.getRequestProperties(); /* do post */ if (method == Method.POST) { InputStream is; if (params.hasMultipartParams()) { is = params.getMultipart().getContent(); } else { is = new ByteArrayInputStream(params.getParamString().getBytes()); } final OutputStream os = conn.getOutputStream(); writeStream(os, is); } else { conn.connect(); } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.contentEncoding = conn.getContentEncoding(); response.contentLength = conn.getContentLength(); response.contentType = conn.getContentType(); response.date = conn.getDate(); response.expiration = conn.getExpiration(); response.headerFields = conn.getHeaderFields(); response.ifModifiedSince = conn.getIfModifiedSince(); response.lastModified = conn.getLastModified(); response.responseCode = conn.getResponseCode(); response.responseMessage = conn.getResponseMessage(); /* do get */ if (conn.getResponseCode() < 400) { response.responseBody = readStream(conn.getInputStream()); postSuccess(); } else { response.responseBody = readStream(conn.getErrorStream()); response.throwable = new Exception(response.responseMessage); postError(); } } catch (final Exception e) { if (retries < requestOptions.maxRetries) { retries++; postRetry(); execute(); } else { response.responseBody = e.getMessage(); response.throwable = e; postError(); } } finally { if (conn != null) { conn.disconnect(); } } } private String readStream(final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); final ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } return new String(baf.toByteArray()); } private void writeStream(final OutputStream os, final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } os.write(buffer, 0, read); } if (!canceled) { os.flush(); } try { os.close(); } catch (final IOException e) { } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } } @Override public void handleMessage(final Message msg) { if (msg.what == HttpHandler.MESSAGE_CANCEL) { canceled = true; } } private void postSuccess() { postMessage(HttpHandler.MESSAGE_SUCCESS); } private void postError() { postMessage(HttpHandler.MESSAGE_ERROR); } private void postCancel() { postMessage(HttpHandler.MESSAGE_CANCEL); } private void postStart() { postMessage(HttpHandler.MESSAGE_START); } private void postRetry() { postMessage(HttpHandler.MESSAGE_RETRY); } private void postMessage(final int what) { final Message msg = handler.obtainMessage(); msg.what = what; msg.arg1 = requestId; msg.obj = response; handler.sendMessage(msg); } } ; /* Create a new HandlerRunnable and start it */ final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler); requests.put(requestId, new WeakReference<Handler>(hr)); new Thread(hr).start(); /* Return with the request id */ return requestId; }
From source file:org.openbravo.erpCommon.modules.ImportModule.java
/** * Obtains remotely an obx for the desired moduleVersionID * //from ww w.j a v a2s . co m */ private RemoteModule getRemoteModule(String moduleVersionID) { RemoteModule remoteModule = new RemoteModule(); WebService3ImplServiceLocator loc; WebService3Impl ws = null; String strUrl = ""; boolean isCommercial; try { loc = new WebService3ImplServiceLocator(); ws = loc.getWebService3(); } catch (final Exception e) { log4j.error(e); addLog("@CouldntConnectToWS@", ImportModule.MSG_ERROR); try { ImportModuleData.insertLog(ImportModule.pool, (vars == null ? "0" : vars.getUser()), "", "", "", "Couldn't contact with webservice server", "E"); } catch (final ServletException ex) { log4j.error(ex); } remoteModule.setError(true); return remoteModule; } try { isCommercial = ws.isCommercial(moduleVersionID); strUrl = ws.getURLforDownload(moduleVersionID); } catch (AxisFault e1) { addLog("@" + e1.getFaultCode() + "@", ImportModule.MSG_ERROR); remoteModule.setError(true); return remoteModule; } catch (RemoteException e) { addLog(e.getMessage(), ImportModule.MSG_ERROR); remoteModule.setError(true); return remoteModule; } if (isCommercial && !ActivationKey.isActiveInstance()) { addLog("@NotCommercialModulesAllowed@", ImportModule.MSG_ERROR); remoteModule.setError(true); return remoteModule; } try { URL url = new URL(strUrl); HttpURLConnection conn = null; if (strUrl.startsWith("https://")) { ActivationKey ak = ActivationKey.getInstance(); String instanceKey = "obinstance=" + URLEncoder.encode(ak.getPublicKey(), "utf-8"); conn = HttpsUtils.sendHttpsRequest(url, instanceKey); } else { conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("Keep-Alive", "300"); conn.setRequestProperty("Connection", "keep-alive"); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); } if (conn.getResponseCode() == HttpServletResponse.SC_OK) { // OBX is ready to be used remoteModule.setObx(conn.getInputStream()); String size = conn.getHeaderField("Content-Length"); if (size != null) { remoteModule.setSize(new Integer(size)); } return remoteModule; } // There is an error, let's check for a parseable message String msg = conn.getHeaderField("OB-ErrMessage"); if (msg != null) { addLog(msg, ImportModule.MSG_ERROR); } else { addLog("@ErrorDownloadingOBX@ " + conn.getResponseCode(), ImportModule.MSG_ERROR); } } catch (Exception e) { addLog("@ErrorDownloadingOBX@ " + e.getMessage(), ImportModule.MSG_ERROR); } remoteModule.setError(true); return remoteModule; }
From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java
public HttpResponse execute(HashMap<String, File> files) throws HttpClientException { HttpURLConnection conn = null; UncloseableInputStream payloadStream = null; try {/* w ww .j av a 2 s .c o m*/ // 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", "keep-alive"); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setRequestProperty("Accept-Charset", CONTENT_CHARSET); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); if (conn instanceof HttpsURLConnection) { setupSecureConnection(hc.getContext(), (HttpsURLConnection) conn); } // ? StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : parameters.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CONTENT_CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // ??? if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CONTENT_CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } } // ? byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); 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) { 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(); } } }