List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:org.belio.service.gateway.Gateway.java
private synchronized void doPostJson(JSONObject obj) { try {// w w w .j a va 2 s . c o m // String urlParameters = "param1=a¶m2=b¶m3=c"; String request = "http://api.infobip.com/api/v3/sendsms/json"; URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); // connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setUseCaches(false); OutputStream wr = connection.getOutputStream(); // wr.writeBytes(urlParameters); wr.write(obj.toString().getBytes()); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } wr.close(); rd.close(); //s wr.close(); connection.disconnect(); } catch (MalformedURLException ex) { Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex); } catch (ProtocolException ex) { Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Gateway.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:nu.nethome.home.items.hue.JsonRestClient.java
private String performRequest(String baseUrl, String resource, String body, String method) throws IOException { HttpURLConnection connection = null; DataOutputStream wr = null;/*from w w w. java2 s.co m*/ BufferedReader rd = null; StringBuilder sb = new StringBuilder(); String line; URL serverAddress; try { serverAddress = new URL(baseUrl + resource); //Set up the initial connection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); if (body.length() > 0) { connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length)); wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } connection.connect(); if (connection.getResponseCode() < 200 || connection.getResponseCode() > 299) { throw new ProtocolException("Bad HTTP response code: " + connection.getResponseCode()); } rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line); sb.append('\n'); } } finally { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } if (connection != null) { connection.disconnect(); } } return sb.toString(); }
From source file:com.maass.android.imgur_uploader.ImgurUpload.java
/** * This method uploads an image from the given uri. It does the uploading in * small chunks to make sure it doesn't over run the memory. * //from w w w. j ava 2 s . co m * @param uri * image location * @return map containing data from interaction */ private String readPictureDataAndUpload(final Uri uri) { Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)"); try { final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); final int totalFileLength = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); // Create custom progress notification mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress), System.currentTimeMillis()); // set as ongoing mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT; // set custom view to notification mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength); //empty intent for the notification final Intent progressIntent = new Intent(); final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0); mProgressNotification.contentIntent = contentIntent; // add notification to manager mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); final InputStream inputStream = getContentResolver().openInputStream(uri); final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis()) + Long.toHexString((new Random()).nextLong()); final String boundary = "--" + boundaryString; final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json")) .openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\""); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(CHUNK_SIZE); final OutputStream hrout = conn.getOutputStream(); final PrintStream hout = new PrintStream(hrout); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"key\""); hout.println("Content-Type: text/plain"); hout.println(); hout.println(API_KEY); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"image\""); hout.println("Content-Transfer-Encoding: base64"); hout.println(); hout.flush(); { final Base64OutputStream bhout = new Base64OutputStream(hrout); final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES]; int read = 0; int totalRead = 0; long lastLogTime = 0; while (read >= 0) { read = inputStream.read(pictureData); if (read > 0) { bhout.write(pictureData, 0, read); totalRead += read; if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) { lastLogTime = System.currentTimeMillis(); Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength + " bytes (" + (100 * totalRead) / totalFileLength + "%)"); //make a final version of the total read to make the handler happy final int totalReadFinal = totalRead; mHandler.post(new Runnable() { public void run() { mProgressNotification.contentView = generateProgressNotificationView( totalReadFinal, totalFileLength); mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); } }); } bhout.flush(); hrout.flush(); } } Log.d(this.getClass().getName(), "Finishing upload..."); // This close is absolutely necessary, this tells the // Base64OutputStream to finish writing the last of the data // (and including the padding). Without this line, it will miss // the last 4 chars in the output, missing up to 3 bytes in the // final output. bhout.close(); Log.d(this.getClass().getName(), "Upload complete..."); mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead, false); } hout.println(boundary); hout.flush(); hrout.close(); inputStream.close(); Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server"); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder rData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { rData.append(line).append('\n'); } return rData.toString(); } catch (final IOException e) { Log.e(this.getClass().getName(), "Upload failed", e); } return null; }
From source file:nu.nethome.home.items.web.proxy.JsonRestClient.java
private String performRequest(String baseUrl, String resource, String body, String method) throws IOException { HttpURLConnection connection = null; DataOutputStream wr = null;//from w w w . ja v a 2s. c o m BufferedReader rd = null; StringBuilder sb = new StringBuilder(); String line; URL serverAddress; try { serverAddress = new URL(baseUrl + resource); //Set up the initial connection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); connection.setReadTimeout(15000); connection.setInstanceFollowRedirects(false); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); if (body.length() > 0) { connection.setRequestProperty("Content-Length", "" + Integer.toString(body.getBytes().length)); wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); } connection.connect(); if (connection.getResponseCode() < 200 || connection.getResponseCode() > 299) { throw new ProtocolException("Bad HTTP response code: " + connection.getResponseCode()); } rd = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line); sb.append('\n'); } } finally { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } if (connection != null) { connection.disconnect(); } } return sb.toString(); }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? ? /*w ww . j a va 2s . co m*/ * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return ? */ public String uploadMedia(String msgType, String localFile, HttpServletRequest request) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + getAccessToken() + "&type=" + msgType; String local_url = this.getRealPath(request, localFile); // String local_url = localFile; try { File file = new File(local_url); if (!file.exists() || !file.isFile()) { log.error("==" + local_url); return null; } URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); // Post????get? con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post?? // ? con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("content-type", "multipart/form-data; boundary=" + BOUNDARY); // StringBuilder sb = new StringBuilder(); sb.append("--"); // ////////? sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // ? OutputStream out = new DataOutputStream(con.getOutputStream()); out.write(head); // DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// ?? out.write(foot); out.flush(); out.close(); /** * ????,????? */ // con.getResponseCode(); try { // BufferedReader???URL? StringBuffer buffer = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); buffer.append(line); } String respStr = buffer.toString(); log.debug("==respStr==" + respStr); try { JSONObject dataJson = JSONObject.parseObject(respStr); media_id = dataJson.getString("media_id"); } catch (Exception e) { log.error("==respStr==" + respStr, e); try { JSONObject dataJson = JSONObject.parseObject(respStr); return dataJson.getString("errcode"); } catch (Exception e1) { } } } catch (Exception e) { log.error("??POST?" + e); } } catch (Exception e) { log.error("?!=" + local_url); log.error("?!", e); } finally { } return media_id; }
From source file:csic.ceab.movelab.beepath.Util.java
public static boolean uploadFile(byte[] bytes, String filename, String uploadurl) { HttpURLConnection conn = null; DataOutputStream dos = null;/*from w w w . j a v a2 s.c o m*/ // DataInputStream inStream = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 64 * 1024; // old value 1024*1024 ByteArrayInputStream byteArrayInputStream = null; boolean isSuccess = true; try { // ------------------ CLIENT REQUEST byteArrayInputStream = new ByteArrayInputStream(bytes); // open a URL connection to the Servlet URL url = new URL(uploadurl); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don't use a cached copy. conn.setUseCaches(false); // set timeout conn.setConnectTimeout(60000); conn.setReadTimeout(60000); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filename + "\"" + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = byteArrayInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = byteArrayInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = byteArrayInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // close streams // Log.e(TAG,"UploadService Runnable:File is written"); // fileInputStream.close(); // dos.flush(); // dos.close(); } catch (Exception e) { // Log.e(TAG, "UploadService Runnable:Client Request error", e); isSuccess = false; } finally { if (dos != null) { try { dos.close(); } catch (IOException e) { // Log.e(TAG, "exception" + e); } } if (byteArrayInputStream != null) { try { byteArrayInputStream.close(); } catch (IOException e) { // Log.e(TAG, "exception" + e); } } } // ------------------ read the SERVER RESPONSE try { if (conn.getResponseCode() != 200) { isSuccess = false; } } catch (IOException e) { // Log.e(TAG, "Connection error", e); isSuccess = false; } return isSuccess; }
From source file:ch.cyberduck.core.gdocs.GDSession.java
@Override protected void connect() throws IOException { if (this.isConnected()) { return;/*from w ww . ja v a2 s .c o m*/ } this.fireConnectionWillOpenEvent(); GoogleGDataRequest.Factory requestFactory = new GoogleGDataRequest.Factory(); requestFactory.setConnectionSource(new HttpUrlConnectionSource() { public HttpURLConnection openConnection(URL url) throws IOException { return getConnection(url); } }); GoogleAuthTokenFactory authFactory = new GoogleAuthTokenFactory(DocsService.DOCS_SERVICE, this.getUserAgent(), host.getProtocol().getScheme(), "www.google.com", client) { @Override public String getAuthToken(String username, String password, String captchaToken, String captchaAnswer, String serviceName, String applicationName, ClientLoginAccountType accountType) throws AuthenticationException { Map<String, String> params = new HashMap<String, String>(); params.put("Email", username); params.put("Passwd", password); params.put("source", applicationName); params.put("service", serviceName); params.put("accountType", accountType.getValue()); if (captchaToken != null) { params.put("logintoken", captchaToken); } if (captchaAnswer != null) { params.put("logincaptcha", captchaAnswer); } String postOutput; try { URL url = new URL( host.getProtocol().getScheme() + "://" + "www.google.com" + GOOGLE_LOGIN_PATH); postOutput = request(url, params); } catch (IOException e) { AuthenticationException ae = new AuthenticationException( Locale.localizedString("Connection failed", "Error")); ae.initCause(e); throw ae; } // Parse the output Map<String, String> tokenPairs = StringUtil.string2Map(postOutput.trim(), "\n", "=", true); String token = tokenPairs.get("Auth"); if (token == null) { throw getAuthException(tokenPairs); } return token; } /** * Returns the respective {@code AuthenticationException} given the return * values from the login URI handler. * * @param pairs name/value pairs returned as a result of a bad authentication * @return the respective {@code AuthenticationException} for the given error */ private AuthenticationException getAuthException(Map<String, String> pairs) { String errorName = pairs.get("Error"); if ("BadAuthentication".equals(errorName)) { return new GoogleService.InvalidCredentialsException("Invalid credentials"); } else if ("AccountDeleted".equals(errorName)) { return new GoogleService.AccountDeletedException("Account deleted"); } else if ("AccountDisabled".equals(errorName)) { return new GoogleService.AccountDisabledException("Account disabled"); } else if ("NotVerified".equals(errorName)) { return new GoogleService.NotVerifiedException("Not verified"); } else if ("TermsNotAgreed".equals(errorName)) { return new GoogleService.TermsNotAgreedException("Terms not agreed"); } else if ("ServiceUnavailable".equals(errorName)) { return new GoogleService.ServiceUnavailableException("Service unavailable"); } else if ("CaptchaRequired".equals(errorName)) { String captchaPath = pairs.get("CaptchaUrl"); StringBuilder captchaUrl = new StringBuilder(); captchaUrl.append(host.getProtocol().getScheme()).append("://").append("www.google.com") .append(GOOGLE_ACCOUNTS_PATH).append('/').append(captchaPath); return new GoogleService.CaptchaRequiredException("Captcha required", captchaUrl.toString(), pairs.get("CaptchaToken")); } else { return new AuthenticationException("Error authenticating " + "(check service name)"); } } /** * Makes a HTTP POST request to the provided {@code url} given the * provided {@code parameters}. It returns the output from the POST * handler as a String object. * * @param url the URL to post the request * @param parameters the parameters to post to the handler * @return the output from the handler * @throws IOException if an I/O exception occurs while creating, writing, * or reading the request */ private String request(URL url, Map<String, String> parameters) throws IOException { // Open connection HttpURLConnection urlConnection = getConnection(url); // Set properties of the connection urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Form the POST parameters StringBuilder content = new StringBuilder(); boolean first = true; for (Map.Entry<String, String> parameter : parameters.entrySet()) { if (!first) { content.append("&"); } content.append(CharEscapers.uriEscaper().escape(parameter.getKey())).append("="); content.append(CharEscapers.uriEscaper().escape(parameter.getValue())); first = false; } OutputStream outputStream = null; try { outputStream = urlConnection.getOutputStream(); outputStream.write(content.toString().getBytes("utf-8")); outputStream.flush(); } finally { if (outputStream != null) { outputStream.close(); } } // Retrieve the output InputStream inputStream = null; StringBuilder outputBuilder = new StringBuilder(); try { int responseCode = urlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } String string; if (inputStream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); while (null != (string = reader.readLine())) { outputBuilder.append(string).append('\n'); } } } finally { if (inputStream != null) { inputStream.close(); } } return outputBuilder.toString(); } }; client = new DocsService(this.getUserAgent(), requestFactory, authFactory); client.setReadTimeout(this.timeout()); client.setConnectTimeout(this.timeout()); if (this.getHost().getProtocol().isSecure()) { client.useSsl(); } if (!this.isConnected()) { throw new ConnectionCanceledException(); } this.login(); this.fireConnectionDidOpenEvent(); }
From source file:moodle.android.moodle.helpers.MoodleWebService.java
private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters, int xslRawId) { JSONObject jsonobj = null;//from ww w . ja v a2 s. c o m try { HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection(); //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection(); con.setConnectTimeout(30000); con.setReadTimeout(30000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Language", "en-US"); con.setDoOutput(true); con.setUseCaches(false); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); Log.d("URLParameters: ", urlParameters.toString()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = con.getInputStream(); Source xmlSource = new StreamSource(is); Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId)); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); StringWriter writer = new StringWriter(); trans.transform(xmlSource, new StreamResult(writer)); String jsonstr = writer.toString(); jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", ""); jsonstr = jsonstr.replace("</p></div>", ""); jsonstr = jsonstr.replace("<p>", ""); jsonstr = jsonstr.replace("</p>", ""); Log.d("TransformObject: ", jsonstr); jsonobj = new JSONObject(jsonstr); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonobj; }
From source file:mendhak.teamcity.stash.api.StashClient.java
private String PostBuildStatusToStash(String targetURL, String body, String authHeader) { HttpURLConnection connection = null; try {/* w ww . j a va2 s .c o m*/ Logger.LogInfo("Sending build status to " + targetURL); Logger.LogInfo("With body: " + body); Logger.LogInfo("Auth header: " + authHeader); connection = GetConnection(targetURL); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Content-Length", String.valueOf(body.getBytes().length)); connection.setRequestProperty("Authorization", "Basic " + authHeader); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); response.append("\r\n"); } rd.close(); return response.toString(); } catch (Exception e) { Logger.LogError("Could not send data to Stash. ", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:cz.incad.kramerius.k5indexer.Commiter.java
/** * Reads data from the data reader and posts it to solr, writes the response * to output/*from w w w.j av a2 s . c o m*/ */ private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(config.getInt("http.timeout", 10000)); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", contentType); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); int status = urlc.getResponseCode(); StringBuilder errorStream = new StringBuilder(); try { if (status != HttpURLConnection.HTTP_OK) { errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=") .append(status).append(" "); throw new Exception("URL=" + solrUrl + " HTTP response code=" + status); } Reader reader = new InputStreamReader(in); pipeString(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } InputStream es = urlc.getErrorStream(); if (es != null) { try { Reader reader = new InputStreamReader(es); pipeString(reader, errorStream); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (es != null) { es.close(); } } } if (errorStream.length() > 0) { throw new Exception("postData error: " + errorStream.toString()); } } catch (IOException e) { throw new Exception("Solr has throw an error. Check tomcat log. " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }