Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

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

Usage

From source file:manchester.synbiochem.datacapture.SeekConnector.java

private static Status postForm(HttpURLConnection c, MultipartFormData form) throws IOException {
    c.setInstanceFollowRedirects(false);
    c.setDoOutput(true);
    c.setRequestMethod("POST");
    c.setRequestProperty("Content-Type", form.contentType());
    c.setRequestProperty("Content-Length", form.length());
    c.connect();/*from ww w  .  jav a  2  s  .  c om*/
    try (OutputStream os = c.getOutputStream()) {
        os.write(form.content());
    }
    return fromStatusCode(c.getResponseCode());
}

From source file:Main.java

public static String request(String url, Map<String, String> cookies, Map<String, String> parameters)
        throws Exception {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36");
    if (cookies != null && !cookies.isEmpty()) {
        StringBuilder cookieHeader = new StringBuilder();
        for (String cookie : cookies.values()) {
            if (cookieHeader.length() > 0) {
                cookieHeader.append(";");
            }//from  w w  w. j  a  va 2s. co m
            cookieHeader.append(cookie);
        }
        connection.setRequestProperty("Cookie", cookieHeader.toString());
    }
    connection.setDoInput(true);
    if (parameters != null && !parameters.isEmpty()) {
        connection.setDoOutput(true);
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(parametersToWWWFormURLEncoded(parameters));
        osw.flush();
        osw.close();
    }
    if (cookies != null) {
        for (Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) {
            if (headerEntry != null && headerEntry.getKey() != null
                    && headerEntry.getKey().equalsIgnoreCase("Set-Cookie")) {
                for (String header : headerEntry.getValue()) {
                    for (HttpCookie httpCookie : HttpCookie.parse(header)) {
                        cookies.put(httpCookie.getName(), httpCookie.toString());
                    }
                }
            }
        }
    }
    Reader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringWriter w = new StringWriter();
    char[] buffer = new char[1024];
    int n = 0;
    while ((n = r.read(buffer)) != -1) {
        w.write(buffer, 0, n);
    }
    r.close();
    return w.toString();
}

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;/* w  ww  .ja v  a 2s .  c o m*/
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}

From source file:com.avinashbehera.sabera.network.HttpClient.java

public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) {

    URL sendUrl;/*  ww w  . ja v  a  2 s .com*/
    try {
        sendUrl = new URL(url);
    } catch (MalformedURLException e) {
        Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL");
        return null;
    }

    HttpURLConnection conn = null;

    try {
        conn = (HttpURLConnection) sendUrl.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(1024);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + "");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        //writer.write(getPostDataStringfromJsonObject(jsonObjSend));
        Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString());
        //writer.write(jsonObjSend.toString());
        writer.write(String.valueOf(jsonObjSend));

        writer.flush();
        writer.close();
        os.close();

        int responseCode = conn.getResponseCode();
        Log.d(TAG, "responseCode = " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {

            Log.d(TAG, "responseCode = HTTP OK");

            InputStream instream = conn.getInputStream();

            String resultString = convertStreamToString(instream);
            instream.close();
            Log.d(TAG, "resultString = " + resultString);
            //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONParser parser = new JSONParser();
            JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");

            return jsonObjRecv;

        }

    } catch (Exception e) {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return null;

}

From source file:com.example.scandevice.MainActivity.java

public static String excutePost(String targetURL, String urlParameters) {
    URL url;//from  w w  w . j  a va 2 s. c  o m
    HttpURLConnection connection = null;
    try {
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("charset", "utf-8");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

    } catch (Exception e) {
        e.printStackTrace();
        return "Don't post data";

    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }
    return "Data Sent";
}

From source file:com.fota.Link.sdpApi.java

public static String getNcnInfo(String CTN) throws JDOMException {
    String resultStr = "";
    String logData = "";
    try {// ww w.j  a  v a2s  . c  o  m
        String endPointUrl = PropUtil.getPropValue("sdp.oif516.url");

        String strRequest = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' "
                + "xmlns:oas='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'"
                + " xmlns:sdp='http://kt.com/sdp'>" + "     <soapenv:Header>" + "         <oas:Security>"
                + "             <oas:UsernameToken>" + "                 <oas:Username>"
                + PropUtil.getPropValue("sdp.id") + "</oas:Username>" + "                 <oas:Password>"
                + PropUtil.getPropValue("sdp.pw") + "</oas:Password>" + "             </oas:UsernameToken>"
                + "         </oas:Security>" + "     </soapenv:Header>"

                + "     <soapenv:Body>" + "         <sdp:getBasicUserInfoAndMarketInfoRequest>"
                + "         <!--You may enterthe following 6 items in any order-->"
                + "             <sdp:CALL_CTN>" + CTN + "</sdp:CALL_CTN>"
                + "         </sdp:getBasicUserInfoAndMarketInfoRequest>\n" + "     </soapenv:Body>\n"
                + "</soapenv:Envelope>";

        logData = "\r\n---------- Get Ncn Req Info start ----------\r\n";
        logData += " get Ncn Req Info - endPointUrl : " + endPointUrl;
        logData += "\r\n get Ncn Req Info - Content-type : text/xml;charset=utf-8";
        logData += "\r\n get Ncn Req Info - RequestMethod : POST";
        logData += "\r\n get Ncn Req Info - xml : " + strRequest;
        logData += "\r\n---------- Get Ncn Req Info end ----------";

        logger.info(logData);

        // connection
        URL url = new URL(endPointUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Content-type", "text/xml;charset=utf-8");
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        // output
        OutputStream os = connection.getOutputStream();
        // os.write(strRequest.getBytes(), 0, strRequest.length());
        os.write(strRequest.getBytes("utf-8"));
        os.flush();
        os.close();

        // input
        InputStream is = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
        String line = "";
        String resValue = "";
        String parseStr = "";
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            parseStr = line;

        }

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource temp = new InputSource();
        temp.setCharacterStream(new StringReader(parseStr));
        Document doc = builder.parse(temp); //xml?

        NodeList list = doc.getElementsByTagName("*");

        int i = 0;
        Element element;
        String contents;

        String contractNum = "";
        String customerId = "";
        while (list.item(i) != null) {
            element = (Element) list.item(i);
            if (element.hasChildNodes()) {
                contents = element.getFirstChild().getNodeValue();
                System.out.println(element.getNodeName() + " / " + element.getFirstChild().getNodeName());

                if (element.getNodeName().equals("sdp:NS_CONTRACT_NUM")) {
                    //                  resultStr = element.getFirstChild().getNodeValue();
                    contractNum = element.getFirstChild().getNodeValue();
                }
                if (element.getNodeName().equals("sdp:NS_CUSTOMER_ID")) {
                    customerId = element.getFirstChild().getNodeValue();
                }

                //               System.out.println(" >>>>> " + contents);
            }
            i++;
        }

        //         System.out.println("contractNum : " + contractNum + " / cusomerId : " + customerId);

        resultStr = getNcnFromContractnumAndCustomerId(contractNum, customerId);
        //         System.out.println("ncn : " + resultStr);

        //resultStr = resValue;         
        //         resultStr = java.net.URLDecoder.decode(resultStr, "euc-kr");
        connection.disconnect();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return resultStr;
}

From source file:Main.java

public static String postMultiPart(String urlTo, String post, String filepath, String filefield)
        throws ParseException, IOException {
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    String[] q = filepath.split("/");
    int idx = q.length - 1;

    try {/*from ww w  . j a v a2s.c o m*/
        File file = new File(filepath);
        FileInputStream fileInputStream = new FileInputStream(file);

        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        outputStream = new DataOutputStream(connection.getOutputStream());
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\""
                + q[idx] + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd);
        outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
        outputStream.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        outputStream.writeBytes(lineEnd);

        // Upload POST Data
        String[] posts = post.split("&");
        int max = posts.length;
        for (int i = 0; i < max; i++) {
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            String[] kv = posts[i].split("=");
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + kv[0] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(kv[1]);
            outputStream.writeBytes(lineEnd);
        }

        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        inputStream = connection.getInputStream();
        result = convertStreamToString(inputStream);

        fileInputStream.close();
        inputStream.close();
        outputStream.flush();
        outputStream.close();

        return result;
    } catch (Exception e) {
        Log.e("MultipartRequest", "Multipart Form Upload Error");
        e.printStackTrace();
        return "error";
    }
}

From source file:eu.crowdrec.contest.sender.RequestSender.java

/**
 * Send a line from a logFile to an HTTP server (single-threaded).
 * //from   www.  ja  va 2  s.c o  m
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePost(final String logline, final String serverURL) {

    // split the logLine into several token
    String[] token = logline.split("\t");

    String type = token[0];
    String property = token[3];
    String entity = token[4];

    // encode the content as URL parameters.
    String urlParameters = "";
    try {
        urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8"));
    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    // initialize a HTTP connection to the server
    // reuse of connection objects is delegated to the JVM
    HttpURLConnection connection = null;

    try {
        final URL url = new URL(serverURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));

        // Send request
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        // Get Response
        BufferedReader rd = null;
        InputStream is = null;
        try {
            is = connection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is));

            StringBuffer response = new StringBuffer();
            for (String line = rd.readLine(); line != null; line = rd.readLine()) {
                response.append(line);
                response.append(" ");
            }
            return response.toString();
        } catch (IOException e) {
            logger.warn("receivind response failed, ignored.");
        } finally {
            if (is != null) {
                is.close();
            }
            if (rd != null) {
                rd.close();
            }
        }
    } catch (MalformedURLException e) {
        System.err.println("invalid server URL, program stopped.");
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("i/o error connecting the http server, program stopped. e=" + e);
        System.exit(-1);
    } catch (Exception e) {
        System.err.println("general error connecting the http server, program stopped. e:" + e);
        e.printStackTrace();
        System.exit(-1);
    } finally {
        // close the connection
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:com.iStudy.Study.Renren.Util.java

private static HttpURLConnection sendFormdata(String reqUrl, Bundle parameters, String fileParamName,
        String filename, String contentType, byte[] data) {
    HttpURLConnection urlConn = null;
    try {//  w w  w.j  a  v  a2 s .co  m
        URL url = new URL(reqUrl);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setConnectTimeout(5000);// ??jdk
        urlConn.setReadTimeout(5000);// ??jdk 1.5??,?
        urlConn.setDoOutput(true);

        urlConn.setRequestProperty("connection", "keep-alive");

        String boundary = "-----------------------------114975832116442893661388290519"; // 
        urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        boundary = "--" + boundary;
        StringBuffer params = new StringBuffer();
        if (parameters != null) {
            for (Iterator<String> iter = parameters.keySet().iterator(); iter.hasNext();) {
                String name = iter.next();
                String value = parameters.getString(name);
                params.append(boundary + "\r\n");
                params.append("Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n");
                // params.append(URLEncoder.encode(value, "UTF-8"));
                params.append(value);
                params.append("\r\n");
            }
        }

        StringBuilder sb = new StringBuilder();
        sb.append(boundary);
        sb.append("\r\n");
        sb.append("Content-Disposition: form-data; name=\"" + fileParamName + "\"; filename=\"" + filename
                + "\"\r\n");
        sb.append("Content-Type: " + contentType + "\r\n\r\n");
        byte[] fileDiv = sb.toString().getBytes();
        byte[] endData = ("\r\n" + boundary + "--\r\n").getBytes();
        byte[] ps = params.toString().getBytes();

        OutputStream os = urlConn.getOutputStream();
        os.write(ps);
        os.write(fileDiv);
        os.write(data);
        os.write(endData);

        os.flush();
        os.close();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return urlConn;
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

/**
 * Apply normalization rules to the identifier supplied by the End-User 
 * to determine the Resource and Host. Then make an HTTP GET request to
 * the host's WebFinger endpoint to obtain the location of the requested 
 * service//from  w  w  w .j  a  v a 2  s .  c  o m
 * return the issuer location ("href")
 * @param user_input , domain
 * @return
 */

public static String webfinger(String userInput, String serverUrl) {
    // android.os.Debug.waitForDebugger();

    String result = ""; // result of the http request (a json object
    // converted to string)
    String postUrl = "";
    String host = null;
    String href = null;

    // URI identifying the type of service whose location is being requested
    final String rel = "http://openid.net/specs/connect/1.0/issuer";

    if (!isEmpty(userInput)) {

        try {
            // normalizes this URI's path
            URI uri = new URI(userInput).normalize();
            String[] parts = uri.getRawSchemeSpecificPart().split("@");

            if (!isEmpty(serverUrl)) {
                // use serverUrl if specified
                if (serverUrl.startsWith("https://")) {
                    host = serverUrl.substring(8);
                } else if (serverUrl.startsWith("http://")) {
                    host = serverUrl.substring(7);
                } else {
                    host = serverUrl;
                }
            } else if (parts.length > 1) {
                // the user is using an E-Mail Address Syntax
                host = parts[parts.length - 1];
            } else {
                // the user is using an other syntax
                host = uri.getHost();
            }

            // check if host is valid
            if (host == null) {
                return null;
            }

            if (!host.endsWith("/"))
                host += "/";
            postUrl = "https://" + host + ".well-known/webfinger?resource=" + userInput + "&rel=" + rel;

            // log the request
            Logd(TAG, "Web finger request\n GET " + postUrl + "\n HTTP /1.1" + "\n Host: " + host);
            // Send an HTTP get request with the resource and rel parameters
            HttpURLConnection huc = getHUC(postUrl);
            huc.setDoOutput(true);
            huc.setRequestProperty("Content-Type", "application/jrd+json");
            huc.connect();

            try {

                int responseCode = huc.getResponseCode();
                Logd(TAG, "webfinger responseCode: " + responseCode);
                // if 200, read http body
                if (responseCode == 200) {
                    InputStream is = huc.getInputStream();
                    result = convertStreamToString(is);
                    is.close();
                    Logd(TAG, "webfinger result: " + result);

                    // The response is a json object and the issuer location
                    // is returned as the value of the href member
                    // a links array element with the rel member value
                    // http://openid.net/specs/connect/1.0/issuer
                    JSONObject jo = new JSONObject(result);
                    JSONObject links = jo.getJSONArray("links").getJSONObject(0);
                    href = links.getString("href");
                    Logd(TAG, "webfinger reponse href: " + href);

                } else {
                    // why the request didn't succeed
                    href = huc.getResponseMessage();
                }

                // close connection
                huc.disconnect();
            } catch (IOException ioe) {
                Logd(TAG, "webfinger io exception: " + huc.getErrorStream());
                ioe.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        // the user_input is empty
        href = "no identifier detected!!\n";
    }
    return href;
}