Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:xtuaok.sharegyazo.HttpMultipartPostRequest.java

public String send() {
    URLConnection conn = null;
    String res = null;//from w ww.  j a  va 2 s .  c o m
    try {
        conn = new URL(mCgi).openConnection();
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
        ((HttpURLConnection) conn).setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.connect();

        OutputStream os = conn.getOutputStream();
        os.write(createBoundaryMessage("imagedata").getBytes());
        os.write(mByteData);
        String endBoundary = "\r\n--" + BOUNDARY + "--\r\n";
        os.write(endBoundary.getBytes());
        os.close();

        InputStream is = conn.getInputStream();
        res = convertToString(is);
    } catch (Exception e) {
        Log.d(LOG_TAG, e.getMessage() + "");
    } finally {
        if (conn != null) {
            ((HttpURLConnection) conn).disconnect();
        }
    }
    return res;
}

From source file:ext.services.network.Proxy.java

/**
 * Gets the connection./*from  w ww . ja  va 2s .  co m*/
 * 
 * @param u 
 * 
 * @return the connection
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public URLConnection getConnection(URL u) throws IOException {
    URLConnection con = u.openConnection(this);
    String encodedUserPwd = new String(Base64.encodeBase64((user + ':' + password).getBytes()));
    con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
    return con;
}

From source file:org.apache.axis2.transport.testkit.http.JavaNetClient.java

public void sendMessage(ClientOptions options, ContentType contentType, byte[] message) throws Exception {
    URL url = new URL(channel.getEndpointReference().getAddress());
    log.debug("Opening connection to " + url + " using " + URLConnection.class.getName());
    try {//from  w w w .  java  2 s  . co m
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-Type", contentType.toString());
        if (contentType.getBaseType().equals("text/xml")) {
            connection.setRequestProperty("SOAPAction", "");
        }
        OutputStream out = connection.getOutputStream();
        out.write(message);
        out.close();
        if (connection instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            log.debug("Response code: " + httpConnection.getResponseCode());
            log.debug("Response message: " + httpConnection.getResponseMessage());
            int i = 0;
            String headerValue;
            while ((headerValue = httpConnection.getHeaderField(i)) != null) {
                String headerName = httpConnection.getHeaderFieldKey(i);
                if (headerName != null) {
                    log.debug(headerName + ": " + headerValue);
                } else {
                    log.debug(headerValue);
                }
                i++;
            }
        }
        InputStream in = connection.getInputStream();
        IOUtils.copy(in, System.out);
        in.close();
    } catch (IOException ex) {
        log.debug("Got exception", ex);
        throw ex;
    }
}

From source file:io.v.positioning.gae.ServletPostAsyncTask.java

@Override
protected String doInBackground(Context... params) {
    mContext = params[0];/*w  w  w.  j av a  2s  . c  o m*/
    DataOutputStream os = null;
    InputStream is = null;
    try {
        URLConnection conn = mUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.connect();
        os = new DataOutputStream(conn.getOutputStream());
        os.write(mData.toString().getBytes("UTF-8"));
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        return br.readLine();
    } catch (IOException e) {
        return "IOException while contacting GEA: " + e.getMessage();
    } catch (Exception e) {
        return "Exception while contacting GEA: " + e.getLocalizedMessage();
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
                return "IOException closing os: " + e.getMessage();
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                return "IOException closing is: " + e.getMessage();
            }
    }
}

From source file:ar.com.zauber.common.image.impl.JREImageRetriver.java

/**
 * @param uc {@link URLConnection} a preparar.
 *///from w w  w  .  ja  v a 2 s .  co m
private void prepare(final URLConnection uc) {
    uc.setAllowUserInteraction(false);
    uc.setReadTimeout(timeout * 1000);
    if (userAgent != null) {
        uc.setRequestProperty("User-Agent", userAgent);
    }
}

From source file:org.talend.mdm.commmon.util.datamodel.management.SecurityEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)"); //$NON-NLS-1$
        Matcher match = httpUrl.matcher(systemId);
        if (match.matches()) {
            StringBuilder buffer = new StringBuilder();
            String credentials = Base64.encodeBase64String("admin:talend".getBytes()); //$NON-NLS-1$
            URL url = new URL(systemId);
            URLConnection conn = url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);/*from  w  w w .  j  a  v a  2 s.  c o  m*/
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Basic " + credentials); //$NON-NLS-1$
            conn.setRequestProperty("Expect", "100-continue"); //$NON-NLS-1$
            InputStreamReader doc = new InputStreamReader(conn.getInputStream());
            BufferedReader reader = new BufferedReader(doc);
            String line = reader.readLine();
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
            }
            return new InputSource(new StringReader(buffer.toString()));
        } else {
            int mark = systemId.indexOf("file:///"); //$NON-NLS-1$
            String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0)); //$NON-NLS-1$
            File file = new File(path);
            return new InputSource(file.toURL().openStream());
        }

    }
    return null;
}

From source file:com.krawler.esp.handlers.APICallHandlerServiceImpl.java

@Override
public JSONObject callApp(String appURL, JSONObject jData, String companyid, String action, boolean storeCall) {
    String requestData = (jData == null ? "" : jData.toString());

    Apiresponse apires = null;/*from   w w w  .  j a  v a  2s. co m*/
    if (storeCall) {
        apires = makePreEntry(companyid, requestData, action);
    }
    String res = "{success:false}";
    InputStream iStream = null;
    String strSandbox = appURL + API_STRING;
    try {
        URL u = new URL(strSandbox);
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        java.io.PrintWriter pw = new java.io.PrintWriter(uc.getOutputStream());
        pw.println("action=" + action + "&data=" + URLEncoder.encode(requestData, "UTF-8"));
        pw.close();
        iStream = uc.getInputStream();
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(iStream));
        res = URLDecoder.decode(in.readLine(), "UTF-8");
        in.close();
        iStream.close();
    } catch (IOException iex) {
        logger.warn("Remote API call for '" + strSandbox + "' failed because " + iex.getMessage());
    } finally {
        if (iStream != null) {
            try {
                iStream.close();
            } catch (Exception e) {
            }
        }
    }
    JSONObject resObj;
    try {
        resObj = new JSONObject(res);
    } catch (Exception ex) {
        logger.warn("Improper response from Remote API: " + res);
        resObj = new JSONObject();
        try {
            resObj.put("success", false);
        } catch (Exception e) {
        }
    }

    if (storeCall) {
        makePostEntry(apires, res);
    }

    return resObj;
}

From source file:org.gradle.internal.resource.UriResource.java

private Reader getInputStream(URI url) throws IOException {
    final URLConnection urlConnection = url.toURL().openConnection();
    urlConnection.setRequestProperty("User-Agent", getUserAgentString());
    urlConnection.connect();/*from   w  w w  .j ava 2 s  .c  o  m*/
    String charset = extractCharacterEncoding(urlConnection.getContentType(), "utf-8");
    return new InputStreamReader(urlConnection.getInputStream(), charset);
}

From source file:com.amalto.core.util.SecurityEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        Pattern httpUrl = Pattern.compile("(http|https|ftp):(\\//|\\\\)(.*):(.*)");
        Matcher match = httpUrl.matcher(systemId);
        if (match.matches()) {
            StringBuilder buffer = new StringBuilder();
            String credentials = new String(Base64.encodeBase64("admin:talend".getBytes()));
            URL url = new URL(systemId);
            URLConnection conn = url.openConnection();
            conn.setAllowUserInteraction(true);
            conn.setDoOutput(true);//from   w  ww  . ja  va2  s. com
            conn.setDoInput(true);
            conn.setRequestProperty("Authorization", "Basic " + credentials);
            conn.setRequestProperty("Expect", "100-continue");
            InputStreamReader doc = new InputStreamReader(conn.getInputStream());
            BufferedReader reader = new BufferedReader(doc);
            String line = reader.readLine();
            while (line != null) {
                buffer.append(line);
                line = reader.readLine();
            }
            return new InputSource(new StringReader(buffer.toString()));
        } else {
            int mark = systemId.indexOf("file:///");
            String path = systemId.substring((mark != -1 ? mark + "file:///".length() : 0));
            File file = new File(path);
            return new InputSource(file.toURL().openStream());
        }

    }
    return null;
}

From source file:org.apache.sling.sli.SubCommand.java

public void execute() throws Exception {
    Config cfg = sli.getConfig();/*from   ww  w  . j  av a 2  s.c  o m*/
    URL url = new URL(cfg.getProtocol(), cfg.getHostName(), cfg.getPort(), getURI());
    URLConnection connection = url.openConnection();
    String decodedAuth = cfg.getUser() + ":" + cfg.getPassword();
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode(decodedAuth.getBytes()));
    connection.setRequestProperty("Authorization", basicAuth);
    JSONParser parser = new JSONParser();
    InputStream response = connection.getInputStream();
    computeJSON(parser.parse(new BufferedReader(new InputStreamReader(response))));
}