List of usage examples for java.net HttpURLConnection setDoInput
public void setDoInput(boolean doinput)
From source file:com.curso.listadapter.net.RESTClient.java
/** * upload multipart/*w ww .j a v a 2 s. c o m*/ * this method receive the file to be uploaded * */ @SuppressWarnings("deprecation") public String uploadMultiPart(Map<String, File> files) throws Exception { disableSSLCertificateChecking(); Thread.currentThread().setPriority(Thread.MAX_PRIORITY); HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; try { URL endpoint = new URL(url); conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); dos = new DataOutputStream(conn.getOutputStream()); String post = ""; //WRITE ALL THE PARAMS for (NameValuePair p : params) post += writeMultipartParam(p); dos.flush(); //END WRITE ALL THE PARAMS //BEGIN THE UPLOAD ArrayList<FileInputStream> inputStreams = new ArrayList<FileInputStream>(); for (Entry<String, File> entry : files.entrySet()) { post += lineEnd; post += twoHyphens + boundary + lineEnd; String NameParamImage = entry.getKey(); File file = entry.getValue(); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; FileInputStream fileInputStream = new FileInputStream(file); post += "Content-Disposition: attachment; name=\"" + NameParamImage + "\"; filename=\"" + file.getName() + "\"" + lineEnd; String mimetype = getMimeType(file.getName()); post += "Content-Type: " + mimetype + lineEnd; post += "Content-Transfer-Encoding: binary" + lineEnd + lineEnd; dos.write(post.toString().getBytes("UTF-8")); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); inputStreams.add(fileInputStream); } Log.d("Test", post); dos.flush(); post = ""; } //END THE UPLOAD dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens); // for(FileInputStream inputStream: inputStreams){ // inputStream.close(); // } dos.flush(); dos.close(); conn.connect(); Log.d("upload", "finish flush:" + conn.getResponseCode()); } catch (MalformedURLException ex) { Log.e("Debug", "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("Debug", "error: " + ioe.getMessage(), ioe); } try { String response_data = ""; inStream = new DataInputStream(conn.getInputStream()); String str; while ((str = inStream.readLine()) != null) { response_data += str; } inStream.close(); return response_data; } catch (IOException ioex) { Log.e("Debug", "error: " + ioex.getMessage(), ioex); } return null; }
From source file:com.google.glassware.NotifyServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Respond with OK and status 200 in a timely fashion to prevent redelivery response.setContentType("text/html"); Writer writer = response.getWriter(); writer.append("OK"); writer.close();//from w w w .j a v a2s . c o m // Get the notification object from the request body (into a string so we // can log it) BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream())); String notificationString = ""; String responseStringForFaceDetection = null; // Count the lines as a very basic way to prevent Denial of Service attacks int lines = 0; String line; while ((line = notificationReader.readLine()) != null) { notificationString += line; lines++; // No notification would ever be this long. Something is very wrong. if (lines > 1000) { throw new IOException("Attempted to parse notification payload that was unexpectedly long."); } } notificationReader.close(); LOG.info("got raw notification " + notificationString); JsonFactory jsonFactory = new JacksonFactory(); // If logging the payload is not as important, use // jacksonFactory.fromInputStream instead. Notification notification = jsonFactory.fromString(notificationString, Notification.class); LOG.info("Got a notification with ID: " + notification.getItemId()); // Figure out the impacted user and get their credentials for API calls String userId = notification.getUserToken(); Credential credential = AuthUtil.getCredential(userId); Mirror mirrorClient = MirrorClient.getMirror(credential); if (notification.getCollection().equals("locations")) { LOG.info("Notification of updated location"); Mirror glass = MirrorClient.getMirror(credential); // item id is usually 'latest' Location location = glass.locations().get(notification.getItemId()).execute(); LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude()); MirrorClient.insertTimelineItem(credential, new TimelineItem() .setText("Java Quick Start says you are now at " + location.getLatitude() + " by " + location.getLongitude()) .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location) .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE")))); // This is a location notification. Ping the device with a timeline item // telling them where they are. } else if (notification.getCollection().equals("timeline")) { // Get the impacted timeline item TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute(); LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId()); // If it was a share, and contains a photo, update the photo's caption to // acknowledge that we got it. if (notification.getUserActions().contains(new UserAction().setType("SHARE")) && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) { String finalresponseForCard = null; String questionString = timelineItem.getText(); if (!questionString.isEmpty()) { String[] questionStringArray = questionString.split(" "); LOG.info(timelineItem.getText() + " is the questions asked by the user"); LOG.info("A picture was taken"); if (questionString.toLowerCase().contains("search") || questionString.toLowerCase().contains("tag") || questionString.toLowerCase().contains("train") || questionString.toLowerCase().contains("mark") || questionString.toLowerCase().contains("recognize") || questionString.toLowerCase().contains("what is")) { //Fetching the image from the timeline InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(), timelineItem.getAttachments().get(0)); //converting the image to Base64 Base64 base64Object = new Base64(false); String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray() // byteArrayForOutputStream.close(); encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1"); //sending the API request LOG.info("Sending request to API"); //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call try { String urlParameters = ""; String tag = ""; if (questionString.toLowerCase().contains("tag") || questionString.toLowerCase().contains("mark")) { tag = extractTagFromQuestion(questionString); urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag=" + tag + "&base64=" + encodedImageToBase64; } else if (questionString.toLowerCase().contains("train")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1"; } else if (questionString.toLowerCase().contains("search")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64=" + encodedImageToBase64; } else if (questionString.toLowerCase().contains("recognize") || questionString.toLowerCase().contains("what is")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64=" + encodedImageToBase64; } byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8")); int postDataLength = postData.length; String newrequest = "http://rekognition.com/func/api/"; URL url = new URL(newrequest); HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection(); // Increase the timeout for reading the response connectionFaceDetection.setReadTimeout(15000); connectionFaceDetection.setDoOutput(true); connectionFaceDetection.setDoInput(true); connectionFaceDetection.setInstanceFollowRedirects(false); connectionFaceDetection.setRequestMethod("POST"); connectionFaceDetection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connectionFaceDetection.setRequestProperty("X-Mashape-Key", "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp"); connectionFaceDetection.setRequestProperty("charset", "utf-8"); connectionFaceDetection.setRequestProperty("Accept", "application/json"); connectionFaceDetection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connectionFaceDetection.setUseCaches(false); DataOutputStream outputStreamForFaceDetection = new DataOutputStream( connectionFaceDetection.getOutputStream()); outputStreamForFaceDetection.write(postData); BufferedReader inputStreamForFaceDetection = new BufferedReader( new InputStreamReader((connectionFaceDetection.getInputStream()))); StringBuilder responseForFaceDetection = new StringBuilder(); while ((responseStringForFaceDetection = inputStreamForFaceDetection .readLine()) != null) { responseForFaceDetection.append(responseStringForFaceDetection); } //closing all the connections inputStreamForFaceDetection.close(); outputStreamForFaceDetection.close(); connectionFaceDetection.disconnect(); responseStringForFaceDetection = responseForFaceDetection.toString(); LOG.info(responseStringForFaceDetection); JSONObject responseJSONObjectForFaceDetection = new JSONObject( responseStringForFaceDetection); if (questionString.toLowerCase().contains("train") || questionString.contains("tag") || questionString.toLowerCase().contains("mark")) { JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection .getJSONObject("usage"); finalresponseForCard = usageKeyFromResponse.getString("status"); if (!tag.equals("")) finalresponseForCard = "Object is tagged as " + tag; } else { JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection .getJSONObject("scene_understanding"); JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches"); JSONObject firstResultFromArray = matchesArray.getJSONObject(0); double percentSureOfObject; //If an score has value 1, then the value type is Integer else the value type is double if (firstResultFromArray.get("score") instanceof Integer) { percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100; } else percentSureOfObject = (Double) firstResultFromArray.get("score") * 100; finalresponseForCard = "The object is " + firstResultFromArray.getString("tag") + ". Match score is" + percentSureOfObject; } //section where if it doesn't contain anything about tag or train } catch (Exception e) { LOG.warning(e.getMessage()); } } else finalresponseForCard = "Could not understand your words"; } else finalresponseForCard = "Could not understand your words"; TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem(); responseCardForSDKAlchemyAPI.setText(finalresponseForCard); responseCardForSDKAlchemyAPI .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD"))); responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard); responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows"); responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT")); mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute(); LOG.info("New card added to the timeline"); } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) { LOG.info("It was a note taken with the 'take a note' voice command. Processing it."); // Grab the spoken text from the timeline card and update the card with // an HTML response (deleting the text as well). String noteText = timelineItem.getText(); String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)]; timelineItem.setText(null); timelineItem.setHtml(makeHtmlForCard( "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>")); timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE"))); mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute(); } else { LOG.warning("I don't know what to do with this notification, so I'm ignoring it."); } } }
From source file:fr.itldev.koya.services.impl.KoyaContentServiceImpl.java
@Override public InputStream getZipInputStream(User user, List<SecuredItem> securedItems) throws AlfrescoServiceException { HttpURLConnection con; try {/* w w w.j a v a2 s . c o m*/ String urlDownload = getAlfrescoServerUrl() + DOWNLOAD_ZIP_WS_URI + user.getTicketAlfresco(); Map<String, Serializable> params = new HashMap<>(); ArrayList<String> selected = new ArrayList<>(); params.put("nodeRefs", selected); for (SecuredItem item : securedItems) { selected.add(item.getNodeRef()); } JSONObject postParams = new JSONObject(params); con = (HttpURLConnection) new URL(urlDownload).openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.setRequestProperty("Content-Type", "application/json"); con.getOutputStream().write(postParams.toString().getBytes()); return con.getInputStream(); } catch (IOException e) { throw new AlfrescoServiceException(e.getMessage(), e); } }
From source file:calliope.db.CouchConnection.java
/** * Get a document's revid/*from w w w.j a v a2 s .c o m*/ * @param db the database name * @param docID a prepared docID * @return a string or null to indicate it isn't there */ private String getRevId(String db, String docID) throws AeseException { HttpURLConnection conn = null; try { String login = (user == null) ? "" : user + ":" + password + "@"; URL u = new URL("http://" + login + host + ":" + dbPort + "/" + db + "/" + docID); conn = (HttpURLConnection) u.openConnection(); conn.setRequestMethod("HEAD"); conn.setRequestProperty("Content-Type", MIMETypes.JSON); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.connect(); //Get Response String revid = conn.getHeaderField("ETag"); if (revid != null) revid = revid.replaceAll("\"", ""); conn.disconnect(); return revid; } catch (Exception e) { if (conn != null) conn.disconnect(); throw new AeseException(e); } }
From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java
public Boolean upload_v2() { this.downloader.login(); String page = this.downloader.getUrlData(this.URL); String viewstate = ""; Pattern p = Pattern// w ww .j a v a 2 s . co m .compile("<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\" value=\"([^\"]+)\" />"); Matcher m = p.matcher(page); m.find(); viewstate = m.group(1); //System.out.println("viewstate=" + viewstate); // got viewstate InputStream fn_is = null; String raw_upload_data = ""; try { fn_is = new ByteArrayInputStream( ("GC2BNHP,2010-11-07T14:00Z,Write note,\"bla bla\"").getBytes("UTF-8")); raw_upload_data = "GC2BNHP,2010-11-07T20:50Z,Write note,\"bla bla\"".getBytes("UTF-8").toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String cookies_string = this.downloader.getCookies(); ArrayList<InputStream> files = new ArrayList(); files.add(fn_is); Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("ctl00$ContentBody$btnUpload", "Upload Field Note"); ht.put("ctl00$ContentBody$chkSuppressDate", ""); // ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt"); ht.put("__VIEWSTATE", viewstate); HttpData data = HttpRequest.post(this.URL, ht, files, cookies_string); //System.out.println(data.content); String boundary = "----------ThIs_Is_tHe_bouNdaRY_$"; String crlf = "\r\n"; URL url = null; try { url = new URL(this.URL); } catch (MalformedURLException e2) { e2.printStackTrace(); } HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); } catch (IOException e2) { e2.printStackTrace(); } con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); try { con.setRequestMethod("POST"); } catch (java.net.ProtocolException e) { e.printStackTrace(); } con.setRequestProperty("Cookie", cookies_string); //System.out.println("Cookie: " + cookies_string[0] + "=" + cookies_string[1]); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)"); con.setRequestProperty("Pragma", "no-cache"); //con.setRequestProperty("Connection", "Keep-Alive"); String content_type = String.format("multipart/form-data; boundary=%s", boundary); con.setRequestProperty("Content-Type", content_type); DataOutputStream dos = null; try { dos = new DataOutputStream(con.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } String raw_data = ""; // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$btnUpload") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + "Upload Field Note" + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "ctl00$ContentBody$chkSuppressDate") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + "" + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"", "__VIEWSTATE") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + viewstate + crlf; // // raw_data = raw_data + "--" + boundary + crlf; raw_data = raw_data + String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", "ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt") + crlf; raw_data = raw_data + String.format("Content-Type: %s", "text/plain") + crlf; raw_data = raw_data + crlf; raw_data = raw_data + raw_upload_data + crlf; // // raw_data = raw_data + "--" + boundary + "--" + crlf; raw_data = raw_data + crlf; try { this.SendPost(this.URL, raw_data, cookies_string); } catch (IOException e1) { e1.printStackTrace(); } //System.out.println(raw_data); try { dos.writeBytes(raw_data); //dos.writeChars(raw_data); dos.flush(); } catch (IOException e) { e.printStackTrace(); } HttpData ret2 = new HttpData(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(con.getInputStream()), HTMLDownloader.large_buffer_size); String line; while ((line = rd.readLine()) != null) { ret2.content += line + "\r\n"; } } catch (IOException e) { e.printStackTrace(); } //get headers Map<String, List<String>> headers = con.getHeaderFields(); Set<Entry<String, List<String>>> hKeys = headers.entrySet(); for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) { Entry<String, List<String>> m99 = i.next(); //System.out.println("HEADER_KEY" + m99.getKey() + "=" + m99.getValue()); ret2.headers.put(m99.getKey(), m99.getValue().toString()); if (m99.getKey().equals("set-cookie")) ret2.cookies.put(m99.getKey(), m99.getValue().toString()); } try { dos.close(); rd.close(); } catch (IOException e) { e.printStackTrace(); } //System.out.println(ret2.content); //System.out.println("FFFFFFFFFFFFFFFFFFFFFFFFFFFF"); ClientHttpRequest client_req; try { client_req = new ClientHttpRequest(this.URL); String[] cookies_string2 = this.downloader.getCookies2(); for (int jk = 0; jk < cookies_string2.length; jk++) { System.out.println(cookies_string2[jk * 2] + "=" + cookies_string2[(jk * 2) + 1]); client_req.setCookie(cookies_string2[jk * 2], cookies_string2[(jk * 2) + 1]); } client_req.setParameter("ctl00$ContentBody$btnUpload", "Upload Field Note"); client_req.setParameter("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt", fn_is); InputStream response = client_req.post(); //System.out.println(this.convertStreamToString(response)); } catch (IOException e) { e.printStackTrace(); } //ArrayList<InputStream> files = new ArrayList(); files.clear(); files.add(fn_is); Hashtable<String, String> ht2 = new Hashtable<String, String>(); ht2.put("ctl00$ContentBody$btnUpload", "Upload Field Note"); ht2.put("ctl00$ContentBody$chkSuppressDate", ""); // ht.put("ctl00$ContentBody$FieldNoteLoader", "geocache_visits.txt"); ht2.put("__VIEWSTATE", viewstate); HttpData data3 = HttpRequest.post(this.URL, ht2, files, cookies_string); //System.out.println(data3.content); // String the_page2 = this.downloader.get_reader_mpf(this.URL, raw_data, null, true, boundary); //System.out.println("page2=\n" + the_page2); Boolean ret = false; return ret; }
From source file:com.chaosinmotion.securechat.network.SCNetwork.java
private HttpURLConnection requestWith(Request req) throws IOException { String path = server + req.requestURI; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); if (cookies.getCookieStore().getCookies().size() > 0) { conn.setRequestProperty("Cookie", TextUtils.join(";", cookies.getCookieStore().getCookies())); }// w w w . j av a2 s. c o m conn.setDoInput(true); if (req.params != null) { String jsonString = req.params.toString(); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); os.write(jsonString.getBytes("UTF-8")); os.close(); } return conn; }
From source file:com.murrayc.galaxyzoo.app.provider.client.ZooniverseClient.java
public boolean uploadClassificationSync(final String authName, final String authApiKey, final List<NameValuePair> nameValuePairs) throws UploadException { throwIfNoNetwork();/*w w w . j a va 2 s .co m*/ final HttpURLConnection conn; try { conn = openConnection(getPostUploadUri()); } catch (final IOException e) { Log.error("uploadClassificationSync(): Could not open connection", e); throw new UploadException("Could not open connection.", e); } try { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); } catch (final IOException e) { Log.error("uploadClassificationSync: exception during HTTP connection", e); throw new UploadException("exception during HTTP connection", e); } //Add the authentication details to the headers; //Be careful: The server still returns OK_CREATED even if we provide the wrong Authorization here. //There doesn't seem to be any way to know if it's correct other than checking your recent //classifications in your profile. //See https://github.com/zooniverse/Galaxy-Zoo/issues/184 if ((authName != null) && (authApiKey != null)) { conn.setRequestProperty("Authorization", generateAuthorizationHeader(authName, authApiKey)); } try { writeParamsToHttpPost(conn, nameValuePairs); } catch (final IOException e) { Log.error("uploadClassificationSync: writeParamsToHttpPost() failed", e); throw new UploadException("writeParamsToHttpPost() failed.", e); } //TODO: Is this necessary? conn.connect(); //Get the response: InputStream in = null; try { //Note: At least with okhttp.mockwebserver, getInputStream() will throw an IOException (file //not found) if the response code was an error, such as HTTP_UNAUTHORIZED. in = conn.getInputStream(); final int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_CREATED) { Log.error("uploadClassificationSync: Did not receive the 201 Created status code: " + conn.getResponseCode()); return false; } return true; } catch (final IOException e) { Log.error("uploadClassificationSync: exception during HTTP connection", e); throw new UploadException("exception during HTTP connection", e); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { Log.error("uploadClassificationSync: exception while closing in", e); } } } }
From source file:net.namecoin.NameCoinI2PResolver.HttpSession.java
public String executePost(String postdata) throws HttpSessionException { URL url;/*from ww w. j a v a2 s .c o m*/ HttpURLConnection connection = null; try { //Create connection url = new URL(this.uri); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", POST_CONTENT_TYPE); connection.setRequestProperty("User-Agent", "java"); if (!this.user.isEmpty() && !this.password.isEmpty()) { String authString = this.user + ":" + this.password; String authStringEnc = Base64.encodeBytes(authString.getBytes()); connection.setRequestProperty("Authorization", "Basic " + authStringEnc); } connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(postdata); wr.flush(); wr.close(); //Get Response InputStream is = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\r'); } rd.close(); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new HttpSessionException("Server returned: " + connection.getResponseMessage()); } return response.toString(); } catch (Exception e) { throw new HttpSessionException(e.getMessage()); } finally { if (connection != null) { connection.disconnect(); } } }