Example usage for java.net HttpURLConnection setReadTimeout

List of usage examples for java.net HttpURLConnection setReadTimeout

Introduction

In this page you can find the example usage for java.net HttpURLConnection setReadTimeout.

Prototype

public void setReadTimeout(int timeout) 

Source Link

Document

Sets the read timeout to a specified timeout, in milliseconds.

Usage

From source file:jp.go.nict.langrid.servicecontainer.executor.jsonrpc.DynamicJsonRpcServiceExecutor.java

@Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
    Map<String, Object> mimeHeaders = new HashMap<String, Object>();
    final List<RpcHeader> rpcHeaders = new ArrayList<RpcHeader>();
    Pair<Endpoint, Long> r = preprocessJsonRpc(mimeHeaders, rpcHeaders);
    Endpoint ep = r.getFirst();/*from w w w  .  j  a v  a  2 s.c o  m*/
    long s = System.currentTimeMillis();
    HttpURLConnection con = null;
    JsonRpcResponse ret = null;
    RpcFault fault = null;
    try {
        con = (HttpURLConnection) ep.getAddress().toURL().openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(3000);
        con.setReadTimeout(10000);
        con.setRequestProperty("Accept", "application/json-rpc");
        con.setRequestProperty("Content-type", "application/json-rpc");
        con.setRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.JSON_RPC);
        String authUserName = ep.getUserName();
        String authPassword = ep.getPassword();
        if (authUserName != null && authUserName.length() > 0) {
            String header = authUserName + ":" + ((authPassword != null) ? authPassword : "");
            con.setRequestProperty("Authorization",
                    "Basic " + new String(Base64.encodeBase64(header.getBytes())));
        }
        for (Map.Entry<String, Object> entry : mimeHeaders.entrySet()) {
            con.addRequestProperty(entry.getKey(), entry.getValue().toString());
        }
        OutputStream os = con.getOutputStream();
        JSON.encode(JsonRpcUtil.createRequest(rpcHeaders, method, args), os);
        os.flush();
        InputStream is = null;
        try {
            is = con.getInputStream();
        } catch (IOException e) {
            is = con.getErrorStream();
        } finally {
            if (is != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                is = new DuplicatingInputStream(is, baos);
                try {
                    ret = JSON.decode(is, JsonRpcResponse.class);
                } catch (JSONException e) {
                    fault = new RpcFault("Server.userException", e.toString(),
                            ExceptionUtil.getMessageWithStackTrace(e) + "\nsource: "
                                    + new String(baos.toByteArray(), "UTF-8"));
                }
            } else {
                throw new RuntimeException("failed to open response stream.");
            }
        }
        if (ret.getError() != null) {
            fault = ret.getError();
            throw RpcFaultUtil.rpcFaultToThrowable(ret.getError());
        }
        return converter.convert(ret.getResult(), method.getReturnType());
    } finally {
        long dt = System.currentTimeMillis() - s;
        List<RpcHeader> resHeaders = null;
        if (ret != null && ret.getHeaders() != null) {
            resHeaders = Arrays.asList(ret.getHeaders());
        }
        postprocessJsonRpc(r.getSecond(), dt, con, resHeaders, fault);
        if (con != null)
            con.disconnect();
    }
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Get Command List JSON File From Server
 * //from w  w  w.  j  a  v a2s.  c  o  m
 * @throws IOException
 * @throws MalformedURLException
 * @throws JSONException
 */
public void getCommandsList() throws IOException, MalformedURLException, JSONException {
    // Connect to Intel Galileo get Commands List
    HttpURLConnection httpCon = (HttpURLConnection) commandsJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readCommand = httpCon.getInputStream();
    Scanner scanCommand = new Scanner(readCommand).useDelimiter("\\A");
    // Set stream to String
    String commandFile = scanCommand.hasNext() ? scanCommand.next() : "";
    // Initialize serveFile as read string
    JSONObject commandsList = new JSONObject(commandFile);
    JSONObject temp = (JSONObject) commandsList.get("commands");
    JSONArray comArray = (JSONArray) temp.getJSONArray("command");
    int numberOfCommands = comArray.length();
    commands = new String[numberOfCommands];
    // Fill the Array
    for (int i = 0; i < numberOfCommands; i++) {
        JSONObject commandObject = (JSONObject) comArray.get(i);
        commands[i] = commandObject.getString("text");
    }
    Log.d("JSON", "Loaded " + commands[2]);
    httpCon.disconnect();
}

From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * /* w w  w .  j  a v a 2s  .  co  m*/
 * @param url
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();

    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.windigo.http.client.HttpUrlConnectionClient.java

/**
 * Open http url connection to url and return connection
 * // w  w w  .  ja  v  a2  s .  c om
 * @param request
 * @return {@link HttpURLConnection}
 * @throws MalformedURLException
 * @throws IOException
 */
protected HttpURLConnection openHttpURLConnection(Request request) throws MalformedURLException, IOException {

    HttpURLConnection connection = (HttpURLConnection) new URL(request.getFullUrl()).openConnection();
    connection.setRequestMethod(request.getHttpRequestType().toString());
    connection.setConnectTimeout(GlobalSettings.CONNNECTION_TIMEOUT);
    connection.setReadTimeout(GlobalSettings.CONNECTION_READ_TIMEOUT);
    Logger.log("[Request] Connection timeout setted to : " + GlobalSettings.CONNNECTION_TIMEOUT);
    Logger.log("[Request] Connection read timeout setted to : " + GlobalSettings.CONNECTION_READ_TIMEOUT);

    return connection;

}

From source file:com.googlecode.jsonrpc4j.JsonRpcHttpClient.java

/**
 * Prepares a connection to the server./*www.j a  va 2  s  .c  om*/
 * @param extraHeaders extra headers to add to the request
 * @return the unopened connection
 * @throws IOException
 */
protected HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {

    // create URLConnection
    HttpURLConnection con = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
    con.setConnectTimeout(connectionTimeoutMillis);
    con.setReadTimeout(readTimeoutMillis);
    con.setAllowUserInteraction(false);
    con.setDefaultUseCaches(false);
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setInstanceFollowRedirects(true);
    con.setRequestMethod("POST");

    // do stuff for ssl
    if (HttpsURLConnection.class.isInstance(con)) {
        HttpsURLConnection https = HttpsURLConnection.class.cast(con);
        if (hostNameVerifier != null) {
            https.setHostnameVerifier(hostNameVerifier);
        }
        if (sslContext != null) {
            https.setSSLSocketFactory(sslContext.getSocketFactory());
        }
    }

    // add headers
    con.setRequestProperty("Content-Type", "application/json-rpc");
    for (Entry<String, String> entry : headers.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : extraHeaders.entrySet()) {
        con.setRequestProperty(entry.getKey(), entry.getValue());
    }

    // return it
    return con;
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private boolean ping() {
    log.debug("Attempting to ping {}", url);
    try {//w ww  .java 2  s . c  o  m
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(connectionTimeoutSeconds * 1000);
        connection.setReadTimeout(connectionTimeoutSeconds * 1000);
        connection.setRequestMethod("HEAD");
        connection.setInstanceFollowRedirects(false);

        if (sslService != null && connection instanceof HttpsURLConnection) {
            SSLService service = sslService.service();
            if (service != null) {
                SSLSocketFactory factory = service.getSolarInSocketFactory();
                if (factory != null) {
                    HttpsURLConnection sslConnection = (HttpsURLConnection) connection;
                    sslConnection.setSSLSocketFactory(factory);
                }
            }
        }

        int responseCode = connection.getResponseCode();
        return (responseCode >= 200 && responseCode < 400);
    } catch (IOException e) {
        log.info("Error pinging {}: {}", url, e.getMessage());
        return false;
    }
}

From source file:foam.starwisp.NetworkManager.java

private void Request(String u, String type, String CallbackName) {
    try {/*ww w.  ja  v a2s. c  o m*/
        Log.i("starwisp", "pinging: " + u);
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setUseCaches(false);
        con.setReadTimeout(100000 /* milliseconds */);
        con.setConnectTimeout(150000 /* milliseconds */);
        con.setRequestMethod("GET");
        con.setDoInput(true);
        // Starts the query
        con.connect();
        m_RequestHandler.sendMessage(
                Message.obtain(m_RequestHandler, 0, new ReqMsg(con.getInputStream(), type, CallbackName)));

    } catch (Exception e) {
        Log.i("starwisp", e.toString());
        e.printStackTrace();
    }
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public HttpURLConnection initRequest(String service, String method) throws IOException {
    URL url = new URL(serverURL + WS_URL_PREFIX + service);

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

    if (urlConnection instanceof HttpsURLConnection) {
        ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslContext.getSocketFactory());
    }/* w w  w. j av  a2s .  c om*/

    urlConnection.setRequestMethod(method);
    urlConnection.setConnectTimeout(20000);
    urlConnection.setReadTimeout(30000);

    LogManager.debug(MDMManager.class.getSimpleName(), "init request: " + url.getPath() + " (" + method + ")");

    return urlConnection;
}

From source file:moodle.android.moodle.helpers.MoodleWebService.java

private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters,
        int xslRawId) {
    JSONObject jsonobj = null;/*from w ww.j a  v  a  2 s . com*/

    try {
        HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection();
        //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection();

        con.setConnectTimeout(30000);
        con.setReadTimeout(30000);

        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Content-Language", "en-US");
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setDoInput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        Log.d("URLParameters: ", urlParameters.toString());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        //Get Response
        InputStream is = con.getInputStream();

        Source xmlSource = new StreamSource(is);
        Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId));

        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(xsltSource);
        StringWriter writer = new StringWriter();
        trans.transform(xmlSource, new StreamResult(writer));

        String jsonstr = writer.toString();
        jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", "");
        jsonstr = jsonstr.replace("</p></div>", "");
        jsonstr = jsonstr.replace("<p>", "");
        jsonstr = jsonstr.replace("</p>", "");
        Log.d("TransformObject: ", jsonstr);
        jsonobj = new JSONObject(jsonstr);

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block 
        e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block 
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block 
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonobj;
}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 *
 * @param url//  w  ww .  java  2 s.c o  m
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}