Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

Sets the value of the doInput field for this URLConnection to the specified value.

Usage

From source file:org.belio.service.gateway.Gateway.java

private synchronized void doPostJson(JSONObject obj) {
    try {//from   w w  w .j  av a2  s.com
        // String urlParameters = "param1=a&param2=b&param3=c";
        String request = "http://api.infobip.com/api/v3/sendsms/json";
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("charset", "utf-8");
        // connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setUseCaches(false);

        OutputStream wr = connection.getOutputStream();
        //  wr.writeBytes(urlParameters);
        wr.write(obj.toString().getBytes());
        wr.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
        wr.close();
        rd.close();

        //s wr.close();
        connection.disconnect();
    } catch (MalformedURLException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ProtocolException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:io.warp10.script.functions.URLFETCH.java

@Override
public Object apply(WarpScriptStack stack) throws WarpScriptException {

    if (!stack.isAuthenticated()) {
        throw new WarpScriptException(getName() + " requires the stack to be authenticated.");
    }/*  w ww  .j  a  v  a2 s  .c  o  m*/

    Object o = stack.pop();

    if (!(o instanceof String) && !(o instanceof List)) {
        throw new WarpScriptException(getName() + " expects a URL or list thereof on top of the stack.");
    }

    List<URL> urls = new ArrayList<URL>();

    try {
        if (o instanceof String) {
            urls.add(new URL(o.toString()));
        } else {
            for (Object oo : (List) o) {
                urls.add(new URL(oo.toString()));
            }
        }
    } catch (MalformedURLException mue) {
        throw new WarpScriptException(getName() + " encountered an invalid URL.");
    }

    //
    // Check URLs
    //

    for (URL url : urls) {
        if (!StandaloneWebCallService.checkURL(url)) {
            throw new WarpScriptException(getName() + " encountered an invalid URL '" + url + "'");
        }
    }

    //
    // Check that we do not exceed the maxurlfetch limit
    //

    AtomicLong urlfetchCount = (AtomicLong) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_COUNT);
    AtomicLong urlfetchSize = (AtomicLong) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_SIZE);

    if (urlfetchCount.get()
            + urls.size() > (long) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_LIMIT)) {
        throw new WarpScriptException(getName() + " is limited to "
                + stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_LIMIT) + " calls.");
    }

    List<Object> results = new ArrayList<Object>();

    for (URL url : urls) {
        urlfetchCount.addAndGet(1);

        HttpURLConnection conn = null;

        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(false);
            conn.setRequestMethod("GET");

            byte[] buf = new byte[8192];

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            InputStream in = conn.getInputStream();

            while (true) {
                int len = in.read(buf);

                if (len < 0) {
                    break;
                }

                if (urlfetchSize.get() + baos.size()
                        + len > (long) stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_MAXSIZE)) {
                    throw new WarpScriptException(getName()
                            + " would exceed maximum size of content which can be retrieved via URLFETCH ("
                            + stack.getAttribute(WarpScriptStack.ATTRIBUTE_URLFETCH_MAXSIZE) + " bytes)");
                }

                baos.write(buf, 0, len);
            }

            urlfetchSize.addAndGet(baos.size());

            List<Object> res = new ArrayList<Object>();

            res.add(conn.getResponseCode());
            Map<String, List<String>> hdrs = conn.getHeaderFields();

            if (hdrs.containsKey(null)) {
                List<String> statusMsg = hdrs.get(null);
                if (statusMsg.size() > 0) {
                    res.add(statusMsg.get(0));
                } else {
                    res.add("");
                }
            } else {
                res.add("");
            }
            hdrs.remove(null);
            res.add(hdrs);
            res.add(Base64.encodeBase64String(baos.toByteArray()));

            results.add(res);
        } catch (IOException ioe) {
            throw new WarpScriptException(getName() + " encountered an error while fetching '" + url + "'");
        } finally {
            if (null != conn) {
                conn.disconnect();
            }
        }
    }

    stack.push(results);

    return stack;
}

From source file:com.scm.reader.livescanner.search.SearchRequestBuilder.java

public String query(Map<String, String> params)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException {
    this.responseStatus = -1;
    this.responseBody = null;
    String contentType = "multipart/form-data";

    byte[] image = data.getRequestContent();
    byte[] requestBody = createMultipartRequest(image, params);
    final String dateStr = data.getFormattedDate();

    HttpURLConnection conn = (HttpURLConnection) (new URL(getQueryUrl())).openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);/*from w  w w . j av  a 2  s .  c  om*/
    conn.setDoInput(true);

    conn.setRequestProperty("Content-Type", contentType + "; boundary=" + MULTIPART_BOUNDARY);
    //KA-sign auth
    conn.setRequestProperty("Authorization", getAuthorizationHeader(AUTHENTICATION_METHOD, "POST", requestBody,
            contentType, dateStr, KConfig.getConfig().getPath()));
    //Token auth
    //conn.setRequestProperty("Authorization", "Token " + SECRET_TOKEN);

    conn.setRequestProperty("Accept", "application/json; charset=utf-8");
    conn.setRequestProperty("Date", dateStr);

    System.out.println("REQUESTBODY: " + requestBody.toString());
    conn.getOutputStream().write(requestBody);
    return readHttpResponse(conn);
}

From source file:com.geozen.demo.foursquare.jiramot.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * //  w  w  w  . ja  v  a  2 s. c  o m
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url
 *            - the resource to open: must be a welformed URL
 * @param method
 *            - the HTTP method to use ("GET", "POST", etc.)
 * @param params
 *            - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException
 *             - if the URL format is invalid
 * @throws IOException
 *             - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " GeoZen");

    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.example.pabrto.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;//from   w  ww .  ja v a2  s .  c o  m
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:com.shopgun.android.sdk.network.impl.HttpURLNetwork.java

private HttpURLConnection openConnection(Request<?> request, URL url) throws IOException {

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

    connection.setConnectTimeout(request.getTimeOut());
    connection.setReadTimeout(request.getTimeOut());
    connection.setUseCaches(false);//from   w  w  w  . ja v  a 2  s .  c om
    connection.setDoInput(true);
    connection.setInstanceFollowRedirects(false);

    setHeaders(request, connection);
    setRequestMethod(connection, request);
    return connection;
}

From source file:com.nexmo.sdk.core.client.Client.java

/**
 * Prepare a new connection with necessary custom header fields.
 * @param request The request object.//  w  ww .jav a  2  s  .c om
 *
 * @return A new url connection.
 * @throws IOException if an error occurs while opening the connection.
 */
public HttpURLConnection initConnection(Request request) throws IOException {
    // Generate signature using pre-shared key.
    RequestSigning.constructSignatureForRequestParameters(request.getParams(), request.getSecretKey());

    // Construct connection with necessary custom headers.
    URL url = constructUrlGetConnection(request.getParams(), request.getMethod(), request.getUrl());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setReadTimeout(Defaults.CONNECTION_READ_TIMEOUT);
    connection.setConnectTimeout(Defaults.CONNECTION_TIMEOUT);
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.addRequestProperty(HTTP.CONTENT_ENCODING, Config.PARAMS_ENCODING);
    connection.addRequestProperty(BaseService.OS_FAMILY, Config.OS_ANDROID);
    connection.addRequestProperty(BaseService.OS_REVISION, DeviceProperties.getApiLevel());
    connection.addRequestProperty(BaseService.SDK_REVISION, Config.SDK_REVISION_CODE);

    return connection;
}

From source file:com.upnext.blekit.util.http.HttpClient.java

public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod,
        String payload, String payloadContentType) {
    try {/*from   www.j  a  v  a 2 s  .com*/
        String fullUrl = urlWithParams(path != null ? url + path : url, params);
        L.d("[" + httpMethod + "] " + fullUrl);
        final URLConnection connection = new URL(fullUrl).openConnection();
        if (connection instanceof HttpURLConnection) {
            final HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setDoInput(true);
            if (httpMethod != null) {
                httpConnection.setRequestMethod(httpMethod);
                if (httpMethod.equals("POST")) {
                    connection.setDoOutput(true); // Triggers POST.
                    connection.setRequestProperty("Accept-Charset", "UTF-8");
                    connection.setRequestProperty("Content-Type", payloadContentType);
                }
            } else {
                httpConnection.setRequestMethod(params != null ? "POST" : "GET");
            }
            httpConnection.addRequestProperty("Accept", "application/json");
            httpConnection.connect();
            if (payload != null) {
                OutputStream outputStream = httpConnection.getOutputStream();
                try {
                    if (LOG_RESPONSE) {
                        L.d("[payload] " + payload);
                    }
                    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
                    writer.write(payload);
                    writer.close();
                } finally {
                    outputStream.close();
                }
            }
            InputStream input = null;
            try {
                input = connection.getInputStream();
            } catch (IOException e) {
                // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ).
                final int statusCode = httpConnection.getResponseCode();
                if (statusCode == -1)
                    throw e;
                return new Response<T>(Error.httpError(httpConnection.getResponseCode()));
            }
            final int statusCode = httpConnection.getResponseCode();
            L.d("statusCode " + statusCode);
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
                try {
                    T value = null;
                    if (clazz != Void.class) {
                        if (LOG_RESPONSE || clazz == String.class) {
                            StringBuilder sb = new StringBuilder();
                            BufferedReader br = new BufferedReader(new InputStreamReader(input));
                            String read = br.readLine();
                            while (read != null) {
                                sb.append(read);
                                read = br.readLine();
                            }
                            String response = sb.toString();
                            if (LOG_RESPONSE) {
                                L.d("response " + response);
                            }
                            if (clazz == String.class) {
                                value = (T) response;
                            } else {
                                value = (T) objectMapper.readValue(response, clazz);
                            }
                        } else {
                            value = (T) objectMapper.readValue(input, clazz);
                        }
                    }
                    return new Response<T>(value);
                } catch (JsonMappingException e) {
                    return new Response<T>(Error.serlizerError(e));
                } catch (JsonParseException e) {
                    return new Response<T>(Error.serlizerError(e));
                }
            } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) {
                try {
                    T def = clazz.newInstance();
                    if (LOG_RESPONSE) {
                        L.d("statusCode  == HttpURLConnection.HTTP_NO_CONTENT");
                    }
                    return new Response<T>(def);
                } catch (InstantiationException e) {
                    return new Response<T>(Error.ioError(e));
                } catch (IllegalAccessException e) {
                    return new Response<T>(Error.ioError(e));
                }
            } else {
                if (LOG_RESPONSE) {
                    L.d("error, statusCode " + statusCode);
                }
                return new Response<T>(Error.httpError(statusCode));
            }
        }
        return new Response<T>(Error.ioError(new Exception("Url is not a http link")));
    } catch (IOException e) {
        if (LOG_RESPONSE) {
            L.d("error, ioError " + e);
        }
        return new Response<T>(Error.ioError(e));
    }
}

From source file:com.jiramot.foursquare.android.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String/*w  w w .j  a  v  a2 s. com*/
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Foursquare-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FoursquareAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from w  w  w.  j a  v a  2  s  .c o m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Twitter-Util", method + " URL: " + url);
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " TwitterAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}