Java Code Examples for java.net.HttpURLConnection#setConnectTimeout()

The following examples show how to use java.net.HttpURLConnection#setConnectTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: URIResolver.java    From cxf with Apache License 2.0 6 votes vote down vote up
private HttpURLConnection createInputStream() throws IOException {
    HttpURLConnection huc = (HttpURLConnection)url.openConnection();

    String host = SystemPropertyAction.getPropertyOrNull("http.proxyHost");
    if (host != null) {
        //comment out unused port to pass pmd check
        /*String ports = SystemPropertyAction.getProperty("http.proxyPort");
        int port = 80;
        if (ports != null) {
            port = Integer.parseInt(ports);
        }*/

        String username = SystemPropertyAction.getPropertyOrNull("http.proxy.user");
        String password = SystemPropertyAction.getPropertyOrNull("http.proxy.password");

        if (username != null && password != null) {
            String encoded = Base64Utility.encode((username + ":" + password).getBytes());
            huc.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
        }
    }
    huc.setConnectTimeout(30000);
    huc.setReadTimeout(60000);
    is = huc.getInputStream();
    return huc;
}
 
Example 2
Source File: BiliRoamingApi.java    From BiliRoaming with GNU General Public License v3.0 6 votes vote down vote up
private static String getContent(String urlString) throws IOException {
    URL url = new URL(urlString);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Build", String.valueOf(BuildConfig.VERSION_CODE));
    connection.setConnectTimeout(4000);
    connection.connect();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream inputStream = connection.getInputStream();
        String encoding = connection.getContentEncoding();
        return StreamUtils.getContent(inputStream, encoding);
    }
    return null;
}
 
Example 3
Source File: B6401598.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
static HttpURLConnection getHttpURLConnection(URL url, int timeout) throws IOException {

                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setConnectTimeout(40000);
                httpURLConnection.setReadTimeout(timeout);
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setAllowUserInteraction(false);
                httpURLConnection.setRequestMethod("POST");

                // HttpURLConnection httpURLConnection = new MyHttpURLConnection(url);

                return httpURLConnection;
        }
 
Example 4
Source File: Node.java    From JWebAssembly with Apache License 2.0 5 votes vote down vote up
/**
 * Check if there is a new version of the script engine
 * 
 * @throws IOException
 *             if any error occur
 */
private void download() throws IOException {
    String fileName;
    String ext;
    final String os = System.getProperty( "os.name", "" ).toLowerCase();
    if( os.contains( "windows" ) ) {
        boolean is32 = "32".equals( System.getProperty( "sun.arch.data.model" ) );
        fileName = is32 ? "win-x86" : "win-x64";
        ext = "zip";
    } else if( os.contains( "mac" ) ) {
        fileName = "darwin-x64";
        ext = "tar.gz";
    } else if( os.contains( "linux" ) ) {
        fileName = "linux-x64";
        ext = "tar.gz";
    } else {
        throw new IllegalStateException( "Unknown OS: " + os );
    }
    String urlStr = MessageFormat.format( "{0}v{1}/node-v{1}-{2}.{3}", BASE_URL, REVISION, fileName, ext );

    File target = new File( System.getProperty( "java.io.tmpdir" ) + "/node" );
    File commandDir = new File( target.getAbsolutePath() + MessageFormat.format( "/node-v{1}-{2}", BASE_URL, REVISION, fileName, ext ) );

    if( commandDir.isDirectory() && commandDir.listFiles().length > 0 ) {
        // no download needed
        System.out.println( "\tUP-TP-DATE, use version from " + commandDir );
    } else {
        URL url = new URL( urlStr );
        System.out.println( "\tDownload: " + url );
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout( 5000 );

        InputStream input = conn.getInputStream();

        extractStream( input, "tar.gz".equals( ext ), target );
    }

    command = commandDir.getAbsolutePath();
}
 
Example 5
Source File: SECWebRenderer.java    From mil-sym-java with Apache License 2.0 5 votes vote down vote up
private boolean isPluginServiceAvailable()
{
    try
    {
        int timeoutInSeconds = 1;
        int timeoutInMiliseconds = timeoutInSeconds * 1000;
        String strUrl = "";//TODO: set to actual url;
        java.net.URL url = new java.net.URL(strUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        //urlConn.setInstanceFollowRedirects(false);
        urlConn.setRequestMethod("GET");
        //System.out.println("...");
        urlConn.setConnectTimeout(timeoutInMiliseconds);//seems to connect even if not running
        urlConn.setReadTimeout(timeoutInMiliseconds);//this is the one that matters
        //System.out.println("....");
        urlConn.connect();
        //System.out.println(".....");
        int response = urlConn.getResponseCode();
        //System.out.println("......");
        if(response==HttpURLConnection.HTTP_OK)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch(Exception exc)
    {
        ErrorLogger.LogException("SECWebRenderer", "isPluginServiceAvailable", exc);
        return false;
    }
}
 
Example 6
Source File: Worker.java    From android-vlc-remote with GNU General Public License v3.0 5 votes vote down vote up
@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 (;;) {
        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 hostname = address.getHostName();
                mCallback.onReachable(address, mPort, hostname, responseCode);
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, mPort, e);
        }
    }
}
 
Example 7
Source File: TestBaseUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
public static String getFromHTTP(String url, Time timeout) throws Exception {
	final URL u = new URL(url);
	LOG.info("Accessing URL " + url + " as URL: " + u);

	final long deadline = timeout.toMilliseconds() + System.currentTimeMillis();

	while (System.currentTimeMillis() <= deadline) {
		HttpURLConnection connection = (HttpURLConnection) u.openConnection();
		connection.setConnectTimeout(100000);
		connection.connect();

		if (Objects.equals(HttpResponseStatus.SERVICE_UNAVAILABLE, HttpResponseStatus.valueOf(connection.getResponseCode()))) {
			// service not available --> Sleep and retry
			LOG.debug("Web service currently not available. Retrying the request in a bit.");
			Thread.sleep(100L);
		} else {
			InputStream is;

			if (connection.getResponseCode() >= 400) {
				// error!
				LOG.warn("HTTP Response code when connecting to {} was {}", url, connection.getResponseCode());
				is = connection.getErrorStream();
			} else {
				is = connection.getInputStream();
			}

			return IOUtils.toString(is, ConfigConstants.DEFAULT_CHARSET);
		}
	}

	throw new TimeoutException("Could not get HTTP response in time since the service is still unavailable.");
}
 
Example 8
Source File: JarConverter.java    From J2ME-Loader with Apache License 2.0 5 votes vote down vote up
private void download(String urlStr, File outputJar) throws IOException {
	// Download jar if it is referenced in jad file
	URL url = new URL(getRedirect(urlStr));
	Log.d(TAG, "Downloading " + outputJar.getPath());
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setReadTimeout(30000);
	connection.setConnectTimeout(15000);
	InputStream inputStream = connection.getInputStream();
	OutputStream outputStream = new FileOutputStream(outputJar);
	IOUtils.copy(inputStream, outputStream);
	inputStream.close();
	outputStream.close();
	connection.disconnect();
	Log.d(TAG, "Download complete");
}
 
Example 9
Source File: SentinelUtils.java    From Natty with GNU General Public License v3.0 5 votes vote down vote up
private static HttpURLConnection getConnection(String url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(10 * 1000);
    conn.setReadTimeout(10 * 1000);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");
    return conn;
}
 
Example 10
Source File: DefaultHttpConnector.java    From helios with Apache License 2.0 5 votes vote down vote up
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
                                   final Map<String, List<String>> headers,
                                   final String endpointHost)
    throws IOException {
  if (log.isTraceEnabled()) {
    log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
        Joiner.on(',').withKeyValueSeparator("=").join(headers),
        entity.length, Json.asPrettyStringUnchecked(entity));
  } else {
    log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
  }

  final HttpURLConnection connection = (HttpURLConnection) ipUri.toURL().openConnection();
  handleHttps(connection, endpointHost, hostnameVerifierProvider, extraHttpsHandler);

  connection.setRequestProperty("Accept-Encoding", "gzip");
  connection.setInstanceFollowRedirects(false);
  connection.setConnectTimeout(httpTimeoutMillis);
  connection.setReadTimeout(httpTimeoutMillis);
  for (final Map.Entry<String, List<String>> header : headers.entrySet()) {
    for (final String value : header.getValue()) {
      connection.addRequestProperty(header.getKey(), value);
    }
  }
  if (entity.length > 0) {
    connection.setDoOutput(true);
    connection.getOutputStream().write(entity);
  }

  setRequestMethod(connection, method, connection instanceof HttpsURLConnection);

  return connection;
}
 
Example 11
Source File: PetsciiThread.java    From petscii-bbs with Mozilla Public License 2.0 5 votes vote down vote up
public static DownloadData download(URL url, String userAgent) throws IOException {
    if ("ftp".equalsIgnoreCase(url.getProtocol()))
        return ftpDownload(url);
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", defaultString(userAgent));
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);

        int responseCode = conn.getResponseCode();
        final String contentDisposition = defaultString(conn.getHeaderField("Content-Disposition"));
        final String contentPart = contentDisposition.replaceAll("(?is)^.*?;\\s*?filename=['\"](.*?)['\"].*$", "$1");
        final String filename = isEmpty(contentPart) ? url.toString().replaceAll("(?is)^.*/([^\\?&#]+).*$","$1") : contentPart;
        if (responseCode >= 301 && responseCode <= 399) {
            final String newLocation = conn.getHeaderField("Location");
            return download(new URL(newLocation), userAgent);
        } else if (responseCode >= 200 && responseCode <= 299) {
            conn.connect();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(conn.getInputStream(), baos);
            return new DownloadData(filename, baos.toByteArray());
        } else {
            throw new CbmIOException("Error during download from "+url);
        }
    }
    catch (IOException e) {
        throw new CbmIOException("Timeout during download from "+url);
    }
}
 
Example 12
Source File: Util.java    From ki4a with Apache License 2.0 5 votes vote down vote up
protected static boolean isOnline(Context context)
{
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    //"http://google.com"
    String url_str = PreferenceManager.
                        getDefaultSharedPreferences(context).
                        getString("verify_host_text",
                                    context.getString(R.string.pref_default_verify_host));

    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL(url_str);
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(2000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            }
        } catch (MalformedURLException e1) {
            MyLog.i(TAG, "Couldn't connect [Malformed] " + e1.toString());
        } catch (IOException e) {
            MyLog.i(TAG, "Couldn't connect " + e.toString());
        }
    }
    return false;
}
 
Example 13
Source File: HttpStack.java    From base-imageloader with Apache License 2.0 5 votes vote down vote up
protected HttpURLConnection createConnection(String url) throws IOException
{
    String encodedUrl = Uri.encode(url, ALLOWED_URI_CHARS);
    HttpURLConnection conn = (HttpURLConnection) new URL(encodedUrl).openConnection();
    conn.setConnectTimeout(connectTimeout);
    conn.setReadTimeout(readTimeout);
    return conn;
}
 
Example 14
Source File: Texting.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * Free software method copied and adapted from Voice.java
 * @see http://code.google.com/p/google-voice-java/
 * 
 */
private String sendGvSms(String smsData) {
  Log.i(TAG, "sendGvSms()");
  StringBuilder response = new StringBuilder();
  try {
    // Add the RNR_SE to the message
    smsData += "&" + URLEncoder.encode("_rnr_se", UTF8) + "=" + URLEncoder.encode(rnrSEE, UTF8);
    Log.i(TAG, "smsData = " + smsData);
    URL smsUrl = new URL(GV_SMS_SEND_URL);

    HttpURLConnection smsConn = (HttpURLConnection) smsUrl.openConnection();
    smsConn.setRequestProperty( "Authorization", "GoogleLogin auth=" + authToken );
    smsConn.setRequestProperty("User-agent", USER_AGENT);
    setCookies(smsConn);
    smsConn.setDoOutput(true);
    smsConn.setConnectTimeout(SERVER_TIMEOUT_MS);

    Log.i(TAG, "sms request = " + smsConn);
    OutputStreamWriter callwr = new OutputStreamWriter(smsConn.getOutputStream());
    callwr.write(smsData);
    callwr.flush();

    processCookies(smsConn);
    BufferedReader callrd = new BufferedReader(new InputStreamReader(smsConn.getInputStream()));

    String line;
    while ((line = callrd.readLine()) != null) {
      response.append(line);
      response.append("\n");  // HTTP uses \r\n, but Android is built on Linux, so use Unix line endings
    }
    Log.i(TAG, "sendGvSms:  Sent SMS, response = " + response);

    callwr.close();
    callrd.close();

    if (response.length() == 0) {
      throw new IOException("No Response Data Received.");
    } else {
      return response.toString();
    }
  } catch (IOException e) {
    Log.i(TAG, "IO Error on Send " + e.getMessage(), e);
    return "IO Error Message not sent";
  }
}
 
Example 15
Source File: MixinNetHandlerLoginClient.java    From LiquidBounce with GNU General Public License v3.0 4 votes vote down vote up
@Inject(method = "handleEncryptionRequest", at = @At("HEAD"), cancellable = true)
private void handleEncryptionRequest(S01PacketEncryptionRequest packetIn, CallbackInfo callbackInfo) {
    if(MCLeaks.isAltActive()) {
        final SecretKey secretkey = CryptManager.createNewSharedKey();
        String s = packetIn.getServerId();
        PublicKey publickey = packetIn.getPublicKey();
        String s1 = (new BigInteger(CryptManager.getServerIdHash(s, publickey, secretkey))).toString(16);

        final Session session = MCLeaks.getSession();
        final String server = ((InetSocketAddress) this.networkManager.getRemoteAddress()).getHostName() + ":" + ((InetSocketAddress) this.networkManager.getRemoteAddress()).getPort();

        try {
            final String jsonBody = "{\"session\":\"" + session.getToken() + "\",\"mcname\":\"" + session.getUsername() + "\",\"serverhash\":\"" + s1 + "\",\"server\":\"" + server + "\"}";

            final HttpURLConnection connection = (HttpURLConnection) new URL("https://auth.mcleaks.net/v1/joinserver").openConnection();
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
            connection.setDoOutput(true);

            final DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.write(jsonBody.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();

            final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            final StringBuilder outputBuilder = new StringBuilder();

            String line;
            while((line = reader.readLine()) != null)
                outputBuilder.append(line);

            reader.close();
            final JsonElement jsonElement = new Gson().fromJson(outputBuilder.toString(), JsonElement.class);

            if(!jsonElement.isJsonObject() || !jsonElement.getAsJsonObject().has("success")) {
                this.networkManager.closeChannel(new ChatComponentText("Invalid response from MCLeaks API"));
                callbackInfo.cancel();
                return;
            }

            if(!jsonElement.getAsJsonObject().get("success").getAsBoolean()) {
                String errorMessage = "Received success=false from MCLeaks API";

                if(jsonElement.getAsJsonObject().has("errorMessage"))
                    errorMessage = jsonElement.getAsJsonObject().get("errorMessage").getAsString();

                this.networkManager.closeChannel(new ChatComponentText(errorMessage));
                callbackInfo.cancel();
                return;
            }
        }catch(final Exception e) {
            this.networkManager.closeChannel(new ChatComponentText("Error whilst contacting MCLeaks API: " + e.toString()));
            callbackInfo.cancel();
            return;
        }

        ClientUtils.sendEncryption(networkManager, secretkey, publickey, packetIn);
        callbackInfo.cancel();
    }
}
 
Example 16
Source File: HttpDownloadManager.java    From AppUpdate with Apache License 2.0 4 votes vote down vote up
/**
 * 全部下载
 */
private void fullDownload() {
    listener.start();
    try {
        URL url = new URL(apkUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setReadTimeout(Constant.HTTP_TIME_OUT);
        con.setConnectTimeout(Constant.HTTP_TIME_OUT);
        con.setRequestProperty("Accept-Encoding", "identity");
        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream is = con.getInputStream();
            int length = con.getContentLength();
            int len;
            //当前已下载完成的进度
            int progress = 0;
            byte[] buffer = new byte[1024 * 2];
            File file = FileUtil.createFile(downloadPath, apkName);
            FileOutputStream stream = new FileOutputStream(file);
            while ((len = is.read(buffer)) != -1 && !shutdown) {
                //将获取到的流写入文件中
                stream.write(buffer, 0, len);
                progress += len;
                listener.downloading(length, progress);
            }
            if (shutdown) {
                //取消了下载 同时再恢复状态
                shutdown = false;
                LogUtil.d(TAG, "fullDownload: 取消了下载");
                listener.cancel();
            } else {
                listener.done(file);
            }
            //完成io操作,释放资源
            stream.flush();
            stream.close();
            is.close();
            //重定向
        } else if (con.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM ||
                con.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
            apkUrl = con.getHeaderField("Location");
            con.disconnect();
            LogUtil.d(TAG, "fullDownload: 当前地址是重定向Url,定向后的地址:" + apkUrl);
            fullDownload();
        } else {
            listener.error(new SocketTimeoutException("下载失败:Http ResponseCode = " + con.getResponseCode()));
        }
        con.disconnect();
    } catch (Exception e) {
        listener.error(e);
        e.printStackTrace();
    }
}
 
Example 17
Source File: Locator.java    From ip17mon-java with MIT License 4 votes vote down vote up
public static Locator loadFromNet(String netPath) throws IOException {
    URL url = new URL(netPath);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setConnectTimeout(3000);
    httpConn.setReadTimeout(30 * 1000);
    int responseCode = httpConn.getResponseCode();
    if (responseCode != HttpURLConnection.HTTP_OK) {
        return null;
    }

    int length = httpConn.getContentLength();
    if (length <= 0 || length > 64 * 1024 * 1024) {
        throw new InputMismatchException("invalid ip data");
    }
    InputStream is = httpConn.getInputStream();
    byte[] data = new byte[length];
    int downloaded = 0;
    int read = 0;
    while (downloaded < length) {
        try {
            read = is.read(data, downloaded, length - downloaded);
        } catch (IOException e) {
            is.close();
            throw new IOException("read error");
        }
        if (read < 0) {
            is.close();
            throw new IOException("read error");
        }
        downloaded += read;
    }

    is.close();

    String path = url.getPath();
    if (path.toLowerCase().endsWith("datx")) {
        return loadBinary(data, true);
    } else if (path.toLowerCase().endsWith("dat")) {
        return loadBinary(data, false);
    } else {
        return loadBinaryUnkown(data);
    }
}
 
Example 18
Source File: AuthenticationClient.java    From StreamHub-Android-SDK with MIT License 4 votes vote down vote up
@Override
protected String doInBackground(String... strings) {
    StringBuffer responseBuffer = null;
    InputStream is;
    Uri.Builder uriBuilder = new Uri.Builder()
            .scheme(LivefyreConfig.scheme)
            .authority(LivefyreConfig.identityDomain + "." + environment)
            .appendPath(LivefyreConfig.getConfiguredNetworkID())
            .appendPath("api")
            .appendPath("v1.0")
            .appendPath("public")
            .appendPath("profile");
    try {
        URL url = new URL(uriBuilder.toString());

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestProperty("origin", origin);
        httpURLConnection.setRequestProperty("referer", referer);
        httpURLConnection.setRequestProperty("cookie", cookie);

        httpURLConnection.setRequestMethod("GET");
        if (httpURLConnection.getResponseCode() == 200 || httpURLConnection.getResponseCode() == 201) {
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(10000);
            is = httpURLConnection.getInputStream();
            int ch;
            responseBuffer = new StringBuffer();
            while ((ch = is.read()) != -1) {
                responseBuffer.append((char) ch);
            }
            is.close();

            isOk = true;
        } else {
            isOk = false;
        }

    } catch (IOException e) {
        e.printStackTrace();
        isOk = false;
    }

    return responseBuffer.toString();
}
 
Example 19
Source File: AppbarActivity.java    From letv with Apache License 2.0 4 votes vote down vote up
protected byte[] a(String... strArr) {
    try {
        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(strArr[0]).openConnection();
            httpURLConnection.setConnectTimeout(5000);
            try {
                httpURLConnection.setRequestMethod("GET");
                try {
                    InputStream inputStream = httpURLConnection.getInputStream();
                    try {
                        if (httpURLConnection.getResponseCode() == 200) {
                            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                            byte[] bArr = new byte[1024];
                            while (true) {
                                int read = inputStream.read(bArr);
                                if (read != -1) {
                                    byteArrayOutputStream.write(bArr, 0, read);
                                } else {
                                    byteArrayOutputStream.close();
                                    inputStream.close();
                                    return byteArrayOutputStream.toByteArray();
                                }
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                } catch (IOException e2) {
                    e2.printStackTrace();
                    return null;
                }
            } catch (ProtocolException e3) {
                e3.printStackTrace();
                return null;
            }
        } catch (IOException e22) {
            e22.printStackTrace();
            return null;
        }
    } catch (MalformedURLException e4) {
        e4.printStackTrace();
        return null;
    }
}
 
Example 20
Source File: HttpUtils.java    From sds with Apache License 2.0 4 votes vote down vote up
public static String post(String urlPath, Map<String, Object> params) throws Exception {

        URL url = new URL(urlPath);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(1000);
        connection.setReadTimeout(1000);
        connection.setUseCaches(false);
        connection.addRequestProperty("encoding", CHARSET_NAME);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(HTTP_METHOD);

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        OutputStream os = connection.getOutputStream();
        OutputStreamWriter osr = new OutputStreamWriter(os, CHARSET_NAME);
        BufferedWriter bw = new BufferedWriter(osr);

        /**
         * 构建请求参数
         */
        StringBuilder paramStr = new StringBuilder();
        for (Entry<String, Object> entry : params.entrySet()) {
            if (entry.getValue() == null) {
                continue;
            }

            paramStr.append(entry.getKey())
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue().toString(), CHARSET_NAME))
                    .append("&");
        }

        String paramValue = paramStr.toString();
        if (paramValue.endsWith("&")) {
            paramStr.deleteCharAt(paramValue.length() - 1);
        }

        bw.write(paramStr.toString());
        bw.flush();

        InputStream is = connection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, CHARSET_NAME);
        BufferedReader br = new BufferedReader(isr);

        String line;
        StringBuilder response = new StringBuilder();
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        IOUtils.close(bw);
        IOUtils.close(osr);
        IOUtils.close(os);
        IOUtils.close(br);
        IOUtils.close(isr);
        IOUtils.close(is);

        return response.toString();
    }