Example usage for java.net HttpURLConnection setUseCaches

List of usage examples for java.net HttpURLConnection setUseCaches

Introduction

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

Prototype

public void setUseCaches(boolean usecaches) 

Source Link

Document

Sets the value of the useCaches field of this URLConnection to the specified value.

Usage

From source file:com.vibeosys.utils.dbdownloadv1.DbDownload.java

public String downloadDatabase() {
    boolean flag = false;
    HttpURLConnection urlConnection = null;
    OutputStream myOutput = null;
    byte[] buffer = null;
    InputStream inputStream = null;
    String message = FAIL;/*from  ww w  .  j av a2s . c  o  m*/
    System.out.print(downloadDBURL);
    try {
        URL url = new URL(downloadDBURL);
        urlConnection = (HttpURLConnection) url.openConnection();
        System.out.println("##Request Sent...");

        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setConnectTimeout(20000);
        urlConnection.setReadTimeout(10000);
        urlConnection.connect();

        int Http_Result = urlConnection.getResponseCode();
        String res = urlConnection.getResponseMessage();
        System.out.println(res);
        System.out.println(String.valueOf(Http_Result));
        if (Http_Result == HttpURLConnection.HTTP_OK) {
            String contentType = urlConnection.getContentType();
            inputStream = urlConnection.getInputStream();
            System.out.println(contentType);
            if (contentType.equals("application/octet-stream")) {
                buffer = new byte[1024];
                myOutput = new FileOutputStream(this.dbFile);
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    myOutput.write(buffer, 0, length);
                }
                myOutput.flush();
                myOutput.close();
                inputStream.close();
                flag = true;
                message = SUCCESS;
            } else if (contentType.equals("application/json; charset=UTF-8")) {
                message = FAIL;
                flag = false;
                String responce = convertStreamToString(inputStream);
                System.out.println(responce);

                try {
                    JSONObject jsResponce = new JSONObject(responce);
                    message = jsResponce.getString("message");
                } catch (JSONException e) {
                    // addError(screenName, "Json error in downloadDatabase", e.getMessage());
                    System.out.println(e.toString());
                }
            }
        }

    } catch (Exception ex) {
        System.out.println("##ROrder while downloading database" + ex.toString());
        //addError(screenName, "downloadDatabase", ex.getMessage());
    }
    return message;
}

From source file:com.orange.labs.sdk.RestUtils.java

public void uploadRequest(URL url, File file, String folderIdentifier, final Map<String, String> headers,
        final OrangeListener.Success<JSONObject> success, final OrangeListener.Progress progress,
        final OrangeListener.Error failure) {

    // open a URL connection to the Server
    FileInputStream fileInputStream = null;
    try {/*from   www  .j  a  v  a  2  s . c om*/
        fileInputStream = new FileInputStream(file);

        // Open a HTTP connection to the URL
        HttpURLConnection conn = (HttpsURLConnection) url.openConnection();

        // Allow Inputs & Outputs
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Don't use a Cached Copy
        conn.setUseCaches(false);

        conn.setRequestMethod("POST");

        //
        // Define headers
        //

        // Create an unique boundary
        String boundary = "UploadBoundary";

        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key.toString(), headers.get(key));
        }

        //
        // Write body part
        //
        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

        int bytesAvailable = fileInputStream.available();

        String marker = "\r\n--" + boundary + "\r\n";

        dos.writeBytes(marker);
        dos.writeBytes("Content-Disposition: form-data; name=\"description\"\r\n\r\n");

        // Create JSonObject :
        JSONObject params = new JSONObject();
        params.put("name", file.getName());
        params.put("size", String.valueOf(bytesAvailable));
        params.put("folder", folderIdentifier);

        dos.writeBytes(params.toString());

        dos.writeBytes(marker);
        dos.writeBytes(
                "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
        dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");

        int progressValue = 0;
        int bytesRead = 0;
        byte buf[] = new byte[1024];
        BufferedInputStream bufInput = new BufferedInputStream(fileInputStream);
        while ((bytesRead = bufInput.read(buf)) != -1) {
            // write output
            dos.write(buf, 0, bytesRead);
            dos.flush();
            progressValue += bytesRead;
            // update progress bar
            progress.onProgress((float) progressValue / bytesAvailable);
        }

        dos.writeBytes(marker);

        //
        // Responses from the server (code and message)
        //
        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        // close streams
        fileInputStream.close();
        dos.flush();
        dos.close();

        if (serverResponseCode == 200 || serverResponseCode == 201) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Response: " + line);
                response += line;
            }
            rd.close();
            JSONObject object = new JSONObject(response);
            success.onResponse(object);
        } else {
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            String response = "";
            String line;
            while ((line = rd.readLine()) != null) {
                Log.i("FileUpload", "Error: " + line);
                response += line;
            }
            rd.close();
            JSONObject errorResponse = new JSONObject(response);
            failure.onErrorResponse(new CloudAPIException(serverResponseCode, errorResponse));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:open.dolphin.utilities.common.OrcaApi.java

/**
 * ??/*  w w w. j  a  v a2s  .  c  om*/
 *
 * @param urlInfo URL
 * @param data ?
 * @return
 */
protected String orcaSendRecv(String urlInfo, String data) {
    StringBuilder ret = new StringBuilder();

    try {
        StringBuilder urlStr = new StringBuilder();
        urlStr.append(URL_HTTP);
        urlStr.append(host);
        urlStr.append(":");
        urlStr.append(port);
        urlStr.append(urlInfo);
        URL url = new URL(urlStr.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod(REQUESTMETHOD_POST);
        connection.setRequestProperty("Content-Type", "application/xml");

        byte[] encoded = Base64.encodeBase64((user + ":" + pass).getBytes());
        connection.setRequestProperty("Authorization", "Basic " + new String(encoded));

        connection.setRequestProperty("Content-Length", "" + data.length());
        try (PrintWriter printWriter = new PrintWriter(connection.getOutputStream())) {
            printWriter.printf(data);
        }

        InputStream is = connection.getInputStream();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                ret.append(line);//.append("\n");
            }
        }

        connection.disconnect();
    } catch (MalformedURLException ex) {
        Logger.getLogger(OrcaApi.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(OrcaApi.class.getName()).log(Level.SEVERE, null, ex);
    }

    return ret.toString();
}

From source file:com.koodroid.chicken.KooDroidHelper.java

public void checkForUpdateOnBackgroundThread(final MainActivity activity) {
    if (mAlreadyCheckedForUpdates) {
        return;//from   w w  w  .j  a v a  2  s .  c o  m
    }
    mAlreadyCheckedForUpdates = true;
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            SharedPreferences prefs = activity.getSharedPreferences(KooDroidHelper.class.getName(),
                    Context.MODE_PRIVATE);
            Random random = new Random();
            long interval = random.nextInt(7) + 3; // [3, 10)
            long timestamp = prefs.getLong("LastCheckTimestamp", 0);
            long now = System.currentTimeMillis();
            if ((now - timestamp < interval * 24 * 60 * 60 * 1000) && !DEBUG) {
                return null;
            }
            prefs.edit().putLong("LastCheckTimestamp", now).commit();
            HttpURLConnection urlConnection = null;
            BufferedReader in = null;
            try {

                URL url = new URL(mUpdateUrl);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout(60000);
                urlConnection.setReadTimeout(60000);
                urlConnection.setUseCaches(false);
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200) {
                    InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream());
                    in = new BufferedReader(reader);
                    StringBuilder response = new StringBuilder();
                    for (String line = in.readLine(); line != null; line = in.readLine()) {
                        response.append(line);
                    }

                    try {
                        JSONObject jsonObj = new JSONObject(response.toString());
                        mLatestVersion = jsonObj.getString("version_code");
                        mDownloadUrl = jsonObj.getString("download_url");
                    } catch (JSONException e) {
                        System.out.println("Json parse error");
                        e.printStackTrace();
                    }
                    //                        
                    //                        JSONTokener jsonParser = new JSONTokener(response.toString());    
                    //                        // ?json?JSONObject    
                    //                        // ??"name" : nextValue"yuanzhifei89"String    
                    //                        JSONObject person = (JSONObject) jsonParser.nextValue();    
                    //                        // ?JSON?    
                    //                        person.getJSONArray("phone");    
                    //                        person.getString("name");    
                    //                        person.getInt("age");    
                    //                        person.getJSONObject("address");    
                    //                        person.getBoolean("married");    
                    //                        
                    //mLatestVersion = response.toString();
                    int versionCode = Integer.valueOf(mLatestVersion);
                    mUpdateAvailable = Integer.valueOf(mLatestVersion) > Integer
                            .valueOf(getPackageVersionCode(activity));
                }
            } catch (Exception e) {
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            //maybeShowUpdateDialog(activity);
        }
    }.execute();
}

From source file:com.adr.taskexecutor.ui.TaskExecutorRemote.java

@Override
public void run(TaskExecutor.RunProcess ui) throws Exception {

    URL url;// www.j  a  va  2  s. com
    BufferedReader readerin = null;
    Writer writerout = null;
    try {
        // http://localhost:8084/taskexecutor/executetask?parameter=&loglevel=INFO&trace=false&stats=true&task=
        url = new URL(jURL.getText());

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

        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

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

        String query = "&parameter=" + URLEncoder.encode(parameter, "UTF-8");
        query += "&task=" + URLEncoder.encode(task, "UTF-8");
        query += "&language=" + URLEncoder.encode(language, "UTF-8");
        query += "&loglevel=" + URLEncoder.encode(jLoggingLevel.getSelectedItem().toString(), "UTF-8");
        query += "&trace=" + URLEncoder.encode(Boolean.toString(jTrace.isSelected()), "UTF-8");
        query += "&stats=" + URLEncoder.encode(Boolean.toString(jStats.isSelected()), "UTF-8");

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write("Content-Type: application/x-www- form-urlencoded,encoding=UTF-8\n");
        writerout.write("Content-length: " + String.valueOf(query.length()) + "\n");
        writerout.write("\n");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONParser jsonp = new JSONParser();
            JSONObject json = (JSONObject) jsonp.parse(text.toString());

            // Print lines
            JSONArray jsonlines = (JSONArray) json.get("lines");
            for (Object l : jsonlines) {
                JSONObject jsonline = (JSONObject) l;
                Object type = jsonline.get("type");
                if ("build".equals(type)) {
                    ui.buildMessage((String) jsonline.get("text"));
                } else if ("run".equals(type)) {
                    ui.runMessage((String) jsonline.get("text"));
                } else if ("out".equals(type)) {
                    ui.printOut((String) jsonline.get("text"));
                } else if ("log".equals(type)) {
                    ui.printLog((String) jsonline.get("text"));
                } else if ("success".equals(type)) {
                    ui.successMessage(((Number) jsonline.get("time")).longValue());
                } else if ("fail".equals(type)) {
                    ui.failMessage((String) jsonline.get("text"), ((Number) jsonline.get("time")).longValue());
                } else if ("exception".equals(type)) {
                    ui.exceptionMessage((String) jsonline.get("text"),
                            ((Number) jsonline.get("time")).longValue());
                }
            }

            // Print stats
            ui.getStatsModel().reset();
            JSONArray jsonstats = (JSONArray) json.get("stats");
            if (jsonstats != null) {
                for (Object l : jsonstats) {
                    JSONObject jsonstat = (JSONObject) l;
                    ui.getStatsModel().addRow((String) jsonstat.get("task"), (String) jsonstat.get("step"),
                            ((Number) jsonstat.get("executions")).intValue(),
                            ((Number) jsonstat.get("records")).intValue(),
                            ((Number) jsonstat.get("rejected")).intValue(),
                            ((Number) jsonstat.get("totaltime")).doubleValue(),
                            ((Number) jsonstat.get("avgtime")).doubleValue());
                }
            }

            // save preferences if execution went well
            Configuration.getInstance().setPreference("remote.serverurl", jURL.getText());
            Configuration.getInstance().setPreference("remote.logginglevel",
                    jLoggingLevel.getSelectedItem().toString());
            Configuration.getInstance().setPreference("remote.trace", Boolean.toString(jTrace.isSelected()));
            Configuration.getInstance().setPreference("remote.stats", Boolean.toString(jStats.isSelected()));
            Configuration.getInstance().flushPreferences();

            //                 } catch (NullPointerException ex) {
            //                 } catch (ClassCastException ex) {
            //                 } catch (ParseException ex) {
        } else {
            throw new IOException(MessageFormat.format(bundle.getString("message.httperror"),
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
        //        } catch (MalformedURLException ex) {
        //        } catch (IOException ex) {
    } finally {
        if (writerout != null) {
            try {
                writerout.close();
            } catch (IOException ex) {
            }
            writerout = null;
        }
        if (readerin != null) {
            try {
                readerin.close();
            } catch (IOException ex) {
            }
            readerin = null;
        }
    }
}

From source file:com.google.android.gcm.server.Sender.java

protected HttpURLConnection post(String url, String contentType, String body) throws IOException {
    if (url == null || body == null) {
        throw new IllegalArgumentException("arguments cannot be null");
    }//from www  . jav  a 2  s  . c o m
    if (!url.startsWith("https://")) {
        logger.warning("URL does not use https: " + url);
    }
    logger.fine("Sending POST to " + url);
    logger.finest("POST body: " + body);
    byte[] bytes = body.getBytes(UTF8);
    HttpURLConnection conn = getConnection(url);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", contentType);
    conn.setRequestProperty("Authorization", "key=" + key);
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();
    return conn;
}

From source file:com.yahoo.druid.hadoop.HiveDatasourceInputFormat.java

private String getSegmentsToLoad(String dataSource, List<Interval> intervals, String overlordUrl)
        throws MalformedURLException {
    logger.info("CheckPost7");
    String urlStr = "http://" + overlordUrl + "/druid/indexer/v1/action";
    logger.info("Sending request to overlord at " + urlStr);

    Interval interval = intervals.get(0);

    String requestJson = getSegmentListUsedActionJson(interval.toString());
    logger.info("request json is " + requestJson);

    int numTries = 3;
    for (int trial = 0; trial < numTries; trial++) {
        try {// w  w  w  . j  av a 2  s. c om
            logger.info("attempt number {} to get list of segments from overlord", trial);
            Proxy proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress("httpproxy-prod.blue.ygrid.yahoo.com", 4080));
            URL url = new URL(String.format("%s/druid/coordinator/v1/metadata/datasources/%s/segments?full",
                    overlordUrl, dataSource));
            //new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("content-type", "application/json");
            conn.setRequestProperty("Accept", "*/*");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setConnectTimeout(60000);
            conn.usingProxy();
            OutputStream out = conn.getOutputStream();
            out.write(requestJson.getBytes());
            out.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                return IOUtils.toString(conn.getInputStream());
            } else {
                logger.warn(
                        "Attempt Failed to get list of segments from overlord. response code [%s] , response [%s]",
                        responseCode, IOUtils.toString(conn.getInputStream()));
            }
        } catch (Exception ex) {
            logger.warn("Exception in getting list of segments from overlord", ex);
        }

        try {
            Thread.sleep(5000); //wait before next trial
        } catch (InterruptedException ex) {
            Throwables.propagate(ex);
        }
    }

    throw new RuntimeException(
            String.format("failed to find list of segments, dataSource[%s], interval[%s], overlord[%s]",
                    dataSource, interval, overlordUrl));
}

From source file:com.mercandalli.android.apps.files.common.net.TaskPost.java

@Override
protected String doInBackground(Void... urls) {

    try {//w w  w  . j  a  v a  2s. co  m
        if (this.mParameters != null) {
            if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) {
                mParameters.add(new StringPair("android_id", "" + Config.getNotificationId()));
            }
            url = NetUtils.addUrlParameters(url, mParameters);
        }

        Log.d("TaskGet", "url = " + url);

        final URL tmpUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) tmpUrl.openConnection();
        conn.setReadTimeout(10_000);
        conn.setConnectTimeout(15_000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken());
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        if (this.mParameters != null) {
            final OutputStream outputStream = conn.getOutputStream();
            final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(getQuery(mParameters));
            writer.flush();
            writer.close();
            outputStream.close();
        }

        conn.connect(); // Starts the query
        int responseCode = conn.getResponseCode();
        InputStream inputStream = new BufferedInputStream(conn.getInputStream());

        // convert inputstream to string
        String resultString = convertInputStreamToString(inputStream);

        //int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= 300) {
            resultString = "Status Code " + responseCode + ". " + resultString;
        }

        conn.disconnect();

        return resultString;
    } catch (IOException e) {
        Log.e(getClass().getName(), "Failed to convert Json", e);
    }
    return null;

    //        try {
    //
    //            // http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post
    //
    //            HttpPost httppost = new HttpPost(url);
    //
    //            MultipartEntity mpEntity = new MultipartEntity();
    //            if (this.file != null) mpEntity.addPart("file", new FileBody(file, "*/*"));
    //
    //            String log_parameters = "";
    //            if (this.parameters != null)
    //                for (StringPair b : parameters) {
    //                    mpEntity.addPart(b.getName(), new StringBody(b.getValue(), Charset.forName("UTF-8")));
    //                    log_parameters += b.getName() + ":" + b.getValue() + " ";
    //                }
    //            Log.d("TaskPost", "url = " + url + " " + log_parameters);
    //
    //            httppost.setEntity(mpEntity);
    //
    //            StringBuilder authentication = new StringBuilder().append(app.getConfig().getUser().getAccessLogin()).append(":").append(app.getConfig().getUser().getAccessPassword());
    //            String result = Base64.encodeBytes(authentication.toString().getBytes());
    //            httppost.setHeader("Authorization", "Basic " + result);
    //
    //            HttpClient httpclient = new DefaultHttpClient();
    //            HttpResponse response = httpclient.execute(httppost);
    //
    //            // receive response as inputStream
    //            InputStream inputStream = response.getEntity().getContent();
    //
    //            String resultString = null;
    //
    //            // convert inputstream to string
    //            if (inputStream != null)
    //                resultString = convertInputStreamToString(inputStream);
    //
    //            int responseCode = response.getStatusLine().getStatusCode();
    //            if (responseCode >= 300)
    //                resultString = "Status Code " + responseCode + ". " + resultString;
    //            return resultString;
    //
    //
    //        } catch (UnsupportedEncodingException e) {
    //            e.printStackTrace();
    //        } catch (ClientProtocolException e) {
    //            e.printStackTrace();
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        }
    //        return null;
}

From source file:org.scigap.iucig.controller.ScienceDisciplineController.java

@ResponseBody
@RequestMapping(value = "/updateScienceDiscipline", method = RequestMethod.POST)
public void updateScienceDiscipline(@RequestBody ScienceDiscipline discipline, HttpServletRequest request)
        throws Exception {
    try {/*from  ww  w.j  a  v a 2  s.  co  m*/
        String remoteUser;
        if (request != null) {
            remoteUser = request.getRemoteUser();
        } else {
            throw new Exception("Remote user is null");
        }
        int primarySubDisId = 0;
        int secondarySubDisId = 0;
        int tertiarySubDisId = 0;
        String urlParameters = "user=" + remoteUser;
        if (discipline != null) {
            Map<String, String> primarySubDisc = discipline.getPrimarySubDisc();
            if (primarySubDisc != null && !primarySubDisc.isEmpty()) {
                for (String key : primarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        primarySubDisId = Integer.valueOf(primarySubDisc.get(key));
                        urlParameters += "&discipline1=" + primarySubDisId;
                    }
                }
            } else {
                Map<String, Object> primaryDiscipline = discipline.getPrimaryDisc();
                if (primaryDiscipline != null && !primaryDiscipline.isEmpty()) {
                    Object subdisciplines = primaryDiscipline.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    primarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline1=" + primarySubDisId;
                    }
                }
            }
            Map<String, String> secondarySubDisc = discipline.getSecondarySubDisc();
            if (secondarySubDisc != null && !secondarySubDisc.isEmpty()) {
                for (String key : secondarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        secondarySubDisId = Integer.valueOf(secondarySubDisc.get(key));
                        urlParameters += "&discipline2=" + secondarySubDisId;
                    }
                }
            } else {
                Map<String, Object> secondaryDisc = discipline.getSecondaryDisc();
                if (secondaryDisc != null && !secondaryDisc.isEmpty()) {
                    Object subdisciplines = secondaryDisc.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    secondarySubDisId = Integer
                                            .valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline2=" + secondarySubDisId;
                    }
                }
            }

            Map<String, String> tertiarySubDisc = discipline.getTertiarySubDisc();
            if (tertiarySubDisc != null && !tertiarySubDisc.isEmpty()) {
                for (String key : tertiarySubDisc.keySet()) {
                    if (key.equals("id")) {
                        tertiarySubDisId = Integer.valueOf(tertiarySubDisc.get(key));
                        urlParameters += "&discipline3=" + tertiarySubDisId;
                    }
                }
            } else {
                Map<String, Object> tertiaryDisc = discipline.getTertiaryDisc();
                if (tertiaryDisc != null && !tertiaryDisc.isEmpty()) {
                    Object subdisciplines = tertiaryDisc.get("subdisciplines");
                    if (subdisciplines instanceof ArrayList) {
                        for (int i = 0; i < ((ArrayList) subdisciplines).size(); i++) {
                            Object disc = ((ArrayList) subdisciplines).get(i);
                            if (disc instanceof HashMap) {
                                if (((HashMap) disc).get("name").equals("Other / Unspecified")) {
                                    tertiarySubDisId = Integer.valueOf((((HashMap) disc).get("id")).toString());
                                }
                            }
                        }
                        urlParameters += "&discipline3=" + tertiarySubDisId;
                    }
                }
            }
            URL obj = new URL(SCIENCE_DISCIPLINE_URL + "discipline/");
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            urlParameters += "&date=" + discipline.getDate() + "&source=cybergateway&commit=Update&cluster="
                    + discipline.getCluster();
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();
            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + SCIENCE_DISCIPLINE_URL);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.packpublishing.asynchronousandroid.chapter7.SyncTask.java

@Override
protected Result<JobParameters> doInBackground(JobParameters... params) {
    Log.i(TAG, "SyncTask starting ..");
    Result<JobParameters> result = new Result<JobParameters>();
    result.result = params[0];/*from   w ww.  j a  va2  s .  c  o m*/
    HttpURLConnection urlConn = null;
    try {
        URL url;
        DataOutputStream printout;
        DataInputStream input;
        String file = params[0].getExtras().getString(SYNC_FILE_KEY);
        String endpoint = params[0].getExtras().getString(SYNC_PATH_KEY);
        url = new URL("http://192.168.1.83:4567/" + endpoint);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoInput(true);
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setRequestProperty("Content-Type", "application/json");
        urlConn.connect();
        //Create JSONObject here
        String body = Util.loadJSONFromFile(jobService, file);
        uploadJsonToServer(urlConn, body);

    } catch (Exception e) {
        Log.e("Upload Service", "upload failed", e);
        result.exc = e;
    } finally {
        Log.i(TAG, "SyncTask finished ..");
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
    return result;
}