List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.gson.util.HttpKit.java
/** * // w ww . j av a2 s .co m * @param url * @param params * @param file * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ public static String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ? StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ?? StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream fs = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = fs.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // fs.close(); out.write(end_data); out.flush(); out.close(); // BufferedReader???URL? InputStream in = conn.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (conn != null) { // conn.disconnect(); } return bufferRes.toString(); }
From source file:cloudlens.parser.FileReader.java
public static InputStream fetchFile(String urlString) { try {/*from w w w .j a va 2 s . c o m*/ InputStream inputStream; URL url; if (urlString.startsWith("local:")) { final String path = urlString.replaceFirst("local:", ""); inputStream = Files.newInputStream(Paths.get(path)); } else if (urlString.startsWith("file:")) { url = new URL(urlString); inputStream = Files.newInputStream(Paths.get(url.toURI())); } else if (urlString.startsWith("http:") || urlString.startsWith("https:")) { url = new URL(urlString); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); final Matcher matcher = Pattern.compile("//([^@]+)@").matcher(urlString); if (matcher.find()) { final String encoding = Base64.getEncoder().encodeToString(matcher.group(1).getBytes()); conn.setRequestProperty("Authorization", "Basic " + encoding); } conn.setRequestMethod("GET"); inputStream = conn.getInputStream(); } else { throw new CLException("supported protocols are: http, https, file, and local."); } return inputStream; } catch (IOException | URISyntaxException e) { throw new CLException(e.getMessage()); } }
From source file:com.hichengdai.qlqq.front.util.HttpKit.java
/** * //from ww w.j a v a 2 s. c o m * * @param url * @param params * @param file * @return * @throws IOException * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyManagementException */ public static String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ? StringBuffer bufferRes = null; URL urlGet = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream out = new DataOutputStream(conn.getOutputStream()); byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ?? StringBuilder sb = new StringBuilder(); sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] data = sb.toString().getBytes(); out.write(data); DataInputStream fs = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = fs.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } out.write("\r\n".getBytes()); // fs.close(); out.write(end_data); out.flush(); out.close(); // BufferedReader???URL? InputStream in = conn.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } in.close(); if (conn != null) { // conn.disconnect(); } return bufferRes.toString(); }
From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}.//from w ww. jav a2 s . c om * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. * @author Sections of this code contributed by jTribe (http://jtribe.com.au) */ protected static synchronized String getUrlContent(String sUrl, String email, String pword) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } String userPassword = email + ":" + pword; String encoding = Base64Coder.encodeString(userPassword); try { URL url = new URL(sUrl); System.setProperty("http.keepAlive", "false"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setRequestProperty("User-Agent", sUserAgent); connection.setRequestMethod("GET"); //Get response code int responseCode = connection.getResponseCode(); if (responseCode != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + connection.getResponseMessage()); } // Pull content stream from response InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
From source file:com.fluidops.iwb.luxid.LuxidExtractor.java
public static String useLuxidWS(String input, String token, String outputFormat, String annotationPlan) throws Exception { String s = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=" + "\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> " + "<SOAP-ENV:Body> <ns1:annotateString xmlns:ns1=\"http://luxid.temis.com/ws/types\"> " + "<ns1:sessionKey>" + token + "</ns1:sessionKey> <ns1:plan>" + annotationPlan + "</ns1:plan> <ns1:data>"; s += input;// "This is a great providing test"; s += "</ns1:data> <ns1:consumer>" + outputFormat + "</ns1:consumer> </ns1:annotateString> </SOAP-ENV:Body> " + "</SOAP-ENV:Envelope>"; URL url = new URL("http://193.104.205.28//LuxidWS/services/Annotation"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true);/*from w w w. ja va2 s . c om*/ conn.getOutputStream().write(s.getBytes()); StringBuilder res = new StringBuilder(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = conn.getInputStream(); InputStreamReader read = new InputStreamReader(stream); BufferedReader rd = new BufferedReader(read); String line = ""; StringEscapeUtils.escapeHtml(""); while ((line = rd.readLine()) != null) { res.append(line); } rd.close(); } // res = URLDecoder.decode(res, "UTF-8"); return StringEscapeUtils.unescapeHtml(res.toString().replace("&lt", "<")); }
From source file:com.fluidops.iwb.luxid.LuxidExtractor.java
public static String authenticate() throws Exception { String token = ""; /* ***** Authentication ****** */ String auth = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP-ENV:Body> <ns1:authenticate xmlns:ns1=\"http://luxid.temis.com/ws/types\"> " + "<ns1:userName>" + Config.getConfig().getLuxidUserName() + "</ns1:userName> <ns1:userPassword>" + Config.getConfig().getLuxidPassword() + "</ns1:userPassword> </ns1:authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope>"; URL authURL = new URL(Config.getConfig().getLuxidServerURL()); HttpURLConnection authconn = (HttpURLConnection) authURL.openConnection(); authconn.setRequestMethod("POST"); authconn.setDoOutput(true);// w ww . j a v a 2s . com authconn.getOutputStream().write(auth.getBytes()); if (authconn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = authconn.getInputStream(); InputStreamReader read = new InputStreamReader(stream); BufferedReader rd = new BufferedReader(read); String line = ""; if ((line = rd.readLine()) != null) { token = line.substring(line.indexOf("<token>") + "<token>".length(), line.indexOf("</token>")); } rd.close(); } return token; }
From source file:LNISmokeTest.java
/** * Implement WebDAV PUT http request.//from w w w .ja v a 2s . c o m * * This might be simpler with a real HTTP client library, but * java.net.HttpURLConnection is part of the standard SDK and it * demonstrates the concepts. * * @param lni the lni * @param collHandle the coll handle * @param packager the packager * @param source the source * @param endpoint the endpoint * * @throws RemoteException the remote exception * @throws ProtocolException the protocol exception * @throws IOException Signals that an I/O exception has occurred. * @throws FileNotFoundException the file not found exception */ private static void doPut(LNISoapServlet lni, String collHandle, String packager, String source, String endpoint) throws java.rmi.RemoteException, ProtocolException, IOException, FileNotFoundException { // assemble URL from chopped endpoint-URL and relative URI String collURI = doLookup(lni, collHandle, null); URL url = LNIClientUtils.makeDAVURL(endpoint, collURI, packager); System.err.println("DEBUG: PUT file=" + source + " to URL=" + url.toString()); // connect with PUT method, then copy file over. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("PUT"); conn.setDoOutput(true); fixBasicAuth(url, conn); conn.connect(); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(source); out = conn.getOutputStream(); copyStream(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error("Unable to close input stream", e); } } if (out != null) { try { out.close(); } catch (IOException e) { log.error("Unable to close output stream", e); } } } int status = conn.getResponseCode(); if (status < 200 || status >= 300) { die(status, "HTTP error, status=" + String.valueOf(status) + ", message=" + conn.getResponseMessage()); } // diagnostics, and get resulting new item's location if avail. System.err.println("DEBUG: sent " + source); System.err.println( "RESULT: Status=" + String.valueOf(conn.getResponseCode()) + " " + conn.getResponseMessage()); String loc = conn.getHeaderField("Location"); System.err.println("RESULT: Location=" + ((loc == null) ? "NULL!" : loc)); }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {// w w w . ja va 2s .c o m // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:com.sungtech.goodTeacher.action.TeacherInfoAction.java
public static String httpUrlRequest(String requestURL, String json) { URL url;/* w w w. j a v a 2s .co m*/ String response = ""; HttpURLConnection connection = null; InputStream is = null; try { url = new URL(requestURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.getOutputStream().write(json.getBytes()); connection.getOutputStream().flush(); connection.getOutputStream().close(); int code = connection.getResponseCode(); System.out.println("code" + code); } catch (Exception e) { e.printStackTrace(); } finally { connection.disconnect(); } return response; }
From source file:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java
public static HttpResponse doDelete(URL endpoint, Map<String, String> headers) throws Exception { HttpURLConnection urlConnection = null; try {//ww w.j av a 2s . c o m urlConnection = (HttpURLConnection) endpoint.openConnection(); try { urlConnection.setRequestMethod("DELETE"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support Delete??", e); } urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setUseCaches(false); urlConnection.setAllowUserInteraction(false); // setting headers if (headers != null && headers.size() > 0) { Iterator<String> itr = headers.keySet().iterator(); while (itr.hasNext()) { String key = itr.next(); urlConnection.setRequestProperty(key, headers.get(key)); } } // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } } Iterator<String> itr = urlConnection.getHeaderFields().keySet().iterator(); Map<String, String> responseHeaders = new HashMap(); while (itr.hasNext()) { String key = itr.next(); if (key != null) { responseHeaders.put(key, urlConnection.getHeaderField(key)); } } return new HttpResponse(sb.toString(), urlConnection.getResponseCode(), responseHeaders); } catch (IOException e) { throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } }