Example usage for javax.net.ssl HttpsURLConnection setDoInput

List of usage examples for javax.net.ssl HttpsURLConnection setDoInput

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection 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:com.ibm.mobilefirst.mobileedge.utils.RequestUtils.java

public static void executeTrainRequest(String name, String uuid, List<AccelerometerData> accelerometerData,
        List<GyroscopeData> gyroscopeData, RequestResult requestResult) throws IOException {

    URL url = new URL("https://medge.mybluemix.net/alg/train");

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(5000);/*from   ww  w .j  a v  a  2s.  c  om*/
    conn.setConnectTimeout(10000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    conn.setDoInput(true);
    conn.setDoOutput(true);

    JSONObject jsonToSend = createTrainBodyJSON(name, uuid, accelerometerData, gyroscopeData);

    OutputStream outputStream = conn.getOutputStream();
    DataOutputStream wr = new DataOutputStream(outputStream);
    wr.writeBytes(jsonToSend.toString());
    wr.flush();
    wr.close();

    outputStream.close();

    String response = "";

    int responseCode = conn.getResponseCode();

    //Log.e("BBB2","" + responseCode);

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = br.readLine()) != null) {
            response += line;
        }
    } else {
        response = "{}";
    }

    handleResponse(response, requestResult);
}

From source file:dictinsight.utils.io.HttpUtils.java

/**
 * https??post//from   www.  j  av a  2  s  .c  o  m
 * @param url
 * @param param
 * @return post?
 */
public static String httpsPostData(String url, String param) {
    class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    BufferedOutputStream brOutStream = null;
    BufferedReader reader = null;

    try {
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection();
        connection.setSSLSocketFactory(context.getSocketFactory());
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Proxy-Connection", "Keep-Alive");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setConnectTimeout(1000 * 15);

        brOutStream = new BufferedOutputStream(connection.getOutputStream());
        brOutStream.write(param.getBytes());
        brOutStream.flush();

        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String responseContent = "";
        String line = reader.readLine();
        while (line != null) {
            responseContent += line;
            line = reader.readLine();
        }

        return responseContent;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (brOutStream != null)
                brOutStream.close();
            if (reader != null)
                reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.illusionaryone.GoogleURLShortenerAPIv1.java

@SuppressWarnings("UseSpecificCatch")
private static JSONObject readJsonFromUrl(String urlAddress, String longURL) {
    JSONObject jsonResult = new JSONObject("{}");
    InputStream inputStream = null;
    URL urlRaw;//from www  . jav  a2s. co m
    HttpsURLConnection urlConn;
    String jsonRequest = "";
    String jsonText = "";

    try {
        jsonRequest = "{ 'longUrl': '" + longURL + "'}";
        byte[] postRequest = jsonRequest.getBytes("UTF-8");

        urlRaw = new URL(urlAddress);
        urlConn = (HttpsURLConnection) urlRaw.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("POST");
        urlConn.addRequestProperty("Content-Type", "application/json");
        urlConn.addRequestProperty("Content-Length", String.valueOf(postRequest.length));
        urlConn.addRequestProperty("Accept", "application/vnd.github.v3+json");
        urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 "
                + "(KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015");
        urlConn.connect();
        urlConn.getOutputStream().write(postRequest);

        if (urlConn.getResponseCode() == 200) {
            inputStream = urlConn.getInputStream();
        } else {
            inputStream = urlConn.getErrorStream();
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
        jsonText = readAll(rd);
        jsonResult = new JSONObject(jsonText);
        fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText);
    } catch (JSONException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (UnsupportedEncodingException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "UnsupportedEncodingException", ex.getMessage(),
                jsonText);
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (NullPointerException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (MalformedURLException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (SocketTimeoutException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (IOException ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } catch (Exception ex) {
        fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), "");
        com.gmt2001.Console.err
                .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
    } finally {
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException ex) {
                fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), "");
                com.gmt2001.Console.err
                        .println("GoogleURLShortenerAPIv1::readJsonFromUrl::Exception: " + ex.getMessage());
            }
    }

    return (jsonResult);
}

From source file:com.webarch.common.net.http.HttpService.java

/**
 * ?Https//from w w  w. j a  v  a2 s.  c  o  m
 *
 * @param requestUrl    ?
 * @param requestMethod ?
 * @param trustManagers ??
 * @param outputJson    ?
 * @return 
 */
public static String doHttpsRequest(String requestUrl, String requestMethod, TrustManager[] trustManagers,
        String outputJson) {
    String result = null;
    try {
        StringBuffer buffer = new StringBuffer();
        // SSLContext??
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(requestUrl);
        HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
        httpUrlConn.setSSLSocketFactory(ssf);
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setUseCaches(false);
        httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET);
        httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET);
        // ?GET/POST
        httpUrlConn.setRequestMethod(requestMethod);

        if ("GET".equalsIgnoreCase(requestMethod))
            httpUrlConn.connect();

        // ????
        if (null != outputJson) {
            OutputStream outputStream = httpUrlConn.getOutputStream();
            //??
            outputStream.write(outputJson.getBytes(DEFAULT_CHARSET));
            outputStream.close();
        }

        // ???
        InputStream inputStream = httpUrlConn.getInputStream();
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }
        result = buffer.toString();
        bufferedReader.close();
        inputStreamReader.close();
        // ?
        inputStream.close();
        httpUrlConn.disconnect();
    } catch (ConnectException ce) {
        logger.error("Weixin server connection timed out.", ce);
    } catch (Exception e) {
        logger.error("https request error:", e);
    } finally {
        return result;
    }
}

From source file:org.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];/*from w ww. jav a2 s  .  c  om*/
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

From source file:Main.java

/**
 *
 * @param url - String/*from w w w  . java2 s  .  c o  m*/
 * @param reqParam refer POST method
 * @param accessToken - String
 * @return ArrayList<String> 0: responseBody
 *                          1: responseCode
 */
public static ArrayList<String> getResponse(String url, String reqParam, String accessToken) {
    StringBuilder response = null;
    StringBuilder urlBuilder = null;
    BufferedReader in = null;
    HttpsURLConnection con = null;
    ArrayList<String> responseList = new ArrayList<String>();
    int responseCode = -1;
    try {
        response = new StringBuilder();

        urlBuilder = new StringBuilder();
        urlBuilder.append(url);
        urlBuilder.append("?").append(reqParam);
        urlBuilder.append("&access_token=").append(accessToken);

        URL urlObj = new URL(urlBuilder.toString());

        con = (HttpsURLConnection) urlObj.openConnection();
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.setDoOutput(false);

        con.setRequestProperty("Authorization: Bearer", accessToken);
        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        responseCode = con.getResponseCode();
        String inputLine = "";
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }

    } catch (Exception e) {
        in = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        String inputLine = "";

        try {
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (responseCode == -1) {

        } else {

            System.out.println(response.toString());
        }
    }

    finally {
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    responseList.add(response.toString());
    responseList.add(String.valueOf(responseCode));
    return responseList;

}

From source file:com.ds.kaixin.Util.java

/**
 * http//from  w w  w. ja va2 s.co  m
 * 
 * @param context
 *            
 * @param requestURL
 *            
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-valuekeyvalueString
 *            byte[]
 * @param photos
 *            key-value keyfilename
 *            valueInputStreambyte[]
 *            InputStreamopenUrl
 * @return JSON
 * @throws IOException
 */
public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params,
        Map<String, Object> photos) throws IOException {

    OutputStream os;

    if (httpMethod.equals("GET")) {
        requestURL = requestURL + "?" + encodeUrl(params);
    }

    URL url = new URL(requestURL);
    HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url);

    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK");

    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "close");
    conn.setRequestProperty("Charsert", "UTF-8");

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

        String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // 
        String endLine = "\r\n";

        conn.setRequestMethod("POST");

        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

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

        if (!dataparams.isEmpty()) {

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

        if (photos != null && !photos.isEmpty()) {

            for (String key : photos.keySet()) {

                Object obj = photos.get(key);
                if (obj instanceof InputStream) {
                    InputStream is = (InputStream) obj;
                    try {
                        os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\""
                                + endLine).getBytes());
                        os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                        byte[] data = new byte[UPLOAD_BUFFER_SIZE];
                        int nReadLength = 0;
                        while ((nReadLength = is.read(data)) != -1) {
                            os.write(data, 0, nReadLength);
                        }
                        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                    } finally {
                        try {
                            if (null != is) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Exception on closing input stream", e);
                        }
                    }
                } else if (obj instanceof byte[]) {
                    byte[] byteArray = (byte[]) obj;
                    os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine)
                            .getBytes());
                    os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                    os.write(byteArray);
                    os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                } else {
                    Log.e(LOG_TAG, "");
                }
            }
        }

        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.kaixin.connect.Util.java

/**
 * http//from w ww.jav a  2  s  . c  o m
 * 
 * @param context
 *            
 * @param requestURL
 *            
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-valuekeyvalueStringbyte[]
 * @param photos
 *            key-value keyfilename
 *            valueInputStreambyte[]
 *            InputStreamopenUrl
 * @return JSON
 * @throws IOException
 */
public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params,
        Map<String, Object> photos) throws IOException {

    OutputStream os;

    if (httpMethod.equals("GET")) {
        requestURL = requestURL + "?" + encodeUrl(params);
    }

    URL url = new URL(requestURL);
    HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url);

    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK");

    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "close");
    conn.setRequestProperty("Charsert", "UTF-8");

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

        String BOUNDARY = Util.md5(String.valueOf(System.currentTimeMillis())); // 
        String endLine = "\r\n";

        conn.setRequestMethod("POST");

        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

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

        if (!dataparams.isEmpty()) {

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

        if (photos != null && !photos.isEmpty()) {

            for (String key : photos.keySet()) {

                Object obj = photos.get(key);
                if (obj instanceof InputStream) {
                    InputStream is = (InputStream) obj;
                    try {
                        os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\""
                                + endLine).getBytes());
                        os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                        byte[] data = new byte[UPLOAD_BUFFER_SIZE];
                        int nReadLength = 0;
                        while ((nReadLength = is.read(data)) != -1) {
                            os.write(data, 0, nReadLength);
                        }
                        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                    } finally {
                        try {
                            if (null != is) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Exception on closing input stream", e);
                        }
                    }
                } else if (obj instanceof byte[]) {
                    byte[] byteArray = (byte[]) obj;
                    os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine)
                            .getBytes());
                    os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                    os.write(byteArray);
                    os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                } else {
                    Log.e(LOG_TAG, "");
                }
            }
        }

        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:cn.bidaround.ytcore.kaixin.KaixinUtil.java

/**
 * ??http//from  w  w  w.  j a  v a2  s . c o m
 * 
 * @param context
 *            
 * @param requestURL
 *            ??
 * @param httpMethod
 *            GET  POST
 * @param params
 *            key-value??key???value???Stringbyte[]
 * @param photos
 *            key-value??? keyfilename
 *            value????InputStreambyte[]
 *            ?InputStreamopenUrl?
 * @return ?JSON
 * @throws IOException
 */
public static String openUrl(Context context, String requestURL, String httpMethod, Bundle params,
        Map<String, Object> photos) throws IOException {

    OutputStream os;

    if (httpMethod.equals("GET")) {
        requestURL = requestURL + "?" + encodeUrl(params);
    }

    URL url = new URL(requestURL);
    HttpsURLConnection conn = (HttpsURLConnection) getConnection(context, url);

    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " KaixinAndroidSDK");

    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestProperty("Connection", "close");
    conn.setRequestProperty("Charsert", "UTF-8");

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

        String BOUNDARY = KaixinUtil.md5(String.valueOf(System.currentTimeMillis())); // ?
        String endLine = "\r\n";

        conn.setRequestMethod("POST");

        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

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

        if (!dataparams.isEmpty()) {

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

        if (photos != null && !photos.isEmpty()) {

            for (String key : photos.keySet()) {

                Object obj = photos.get(key);
                if (obj instanceof InputStream) {
                    InputStream is = (InputStream) obj;
                    try {
                        os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\""
                                + endLine).getBytes());
                        os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                        byte[] data = new byte[UPLOAD_BUFFER_SIZE];
                        int nReadLength = 0;
                        while ((nReadLength = is.read(data)) != -1) {
                            os.write(data, 0, nReadLength);
                        }
                        os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                    } finally {
                        try {
                            if (null != is) {
                                is.close();
                            }
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Exception on closing input stream", e);
                        }
                    }
                } else if (obj instanceof byte[]) {
                    byte[] byteArray = (byte[]) obj;
                    os.write(("Content-Disposition: form-data; name=\"pic\";filename=\"" + key + "\"" + endLine)
                            .getBytes());
                    os.write(("Content-Type:application/octet-stream\r\n\r\n").getBytes());
                    os.write(byteArray);
                    os.write((endLine + "--" + BOUNDARY + endLine).getBytes());
                } else {
                    Log.e(LOG_TAG, "?");
                }
            }
        }

        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command./*from  ww  w  . j  a  va2  s  .c om*/
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}