List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:fr.zcraft.zbanque.network.PacketSender.java
private static HTTPResponse makeRequest(String url, PacketPlayOut.PacketType method, String data) throws Throwable { // *** REQUEST *** final URL urlObj = new URL(url); final HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); connection.setRequestMethod(method.name()); connection.setRequestProperty("User-Agent", USER_AGENT); authenticateRequest(connection);//from ww w . ja v a 2 s . c o m connection.setDoOutput(true); try { try { connection.connect(); } catch (IOException ignored) { } if (method == PacketPlayOut.PacketType.POST) { DataOutputStream out = null; try { out = new DataOutputStream(connection.getOutputStream()); if (data != null) out.writeBytes(data); out.flush(); } finally { if (out != null) out.close(); } } // *** RESPONSE *** int responseCode; boolean failed = false; try { responseCode = connection.getResponseCode(); } catch (IOException e) { // HttpUrlConnection will throw an IOException if any 4XX // response is sent. If we request the status again, this // time the internal status will be properly set, and we'll be // able to retrieve it. // Thanks to Iigo. responseCode = connection.getResponseCode(); failed = true; } BufferedReader in = null; String body = ""; try { InputStream stream; try { stream = connection.getInputStream(); } catch (IOException e) { // Same as before stream = connection.getErrorStream(); failed = true; } in = new BufferedReader(new InputStreamReader(stream)); StringBuilder responseBuilder = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { responseBuilder.append(inputLine); } body = responseBuilder.toString(); } finally { if (in != null) in.close(); } HTTPResponse response = new HTTPResponse(); response.setResponseCode(responseCode, failed); response.setResponseBody(body); int i = 0; String headerName, headerContent; while ((headerName = connection.getHeaderFieldKey(i)) != null) { headerContent = connection.getHeaderField(i); response.addHeader(headerName, headerContent); } // *** REDIRECTION *** switch (responseCode) { case 301: case 302: case 307: case 308: if (response.getHeaders().containsKey("Location")) { response = makeRequest(response.getHeaders().get("Location"), method, data); } } // *** END *** return response; } finally { connection.disconnect(); } }
From source file:com.binil.pushnotification.ServerUtil.java
/** * Issue a POST request to the server./*from w w w . ja v a 2 s . co m*/ * * @param endpoint POST address. * @param params request parameters. * @throws java.io.IOException propagated from POST. */ private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException { URL url = new URL(endpoint); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate"); urlConnection.setRequestProperty("Accept", "*/*"); urlConnection.setDoOutput(true); JSONObject json = new JSONObject(params); String body = json.toString(); urlConnection.setFixedLengthStreamingMode(body.length()); try { OutputStream os = urlConnection.getOutputStream(); os.write(body.getBytes("UTF-8")); os.close(); } catch (Exception e) { e.printStackTrace(); } finally { int status = urlConnection.getResponseCode(); String connectionMsg = urlConnection.getResponseMessage(); urlConnection.disconnect(); if (status != HttpURLConnection.HTTP_OK) { Log.wtf(TAG, connectionMsg); throw new IOException("Post failed with error code " + status); } } }
From source file:com.codelanx.codelanxlib.util.auth.UUIDFetcher.java
/** * Opens the connection to Mojang's profile API * //from w w w . ja va2s . com * @since 0.0.1 * @version 0.0.1 * * @return The {@link HttpURLConnection} object to the API server * @throws IOException If there is a problem opening the stream, a malformed * URL, or if there is a ProtocolException */ private static HttpURLConnection createConnection() throws IOException { URL url = new URL(UUIDFetcher.PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:fr.zcraft.zlib.tools.mojang.UUIDFetcher.java
/** * Opens a GET connection.//from w w w .ja va2 s . c om * * @param url The URL to connect to. * * @return A GET connection to this URL. * @throws IOException If an exception occurred while contacting the server. */ static private HttpURLConnection getGETConnection(String url) throws IOException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:com.cyphermessenger.client.SyncRequest.java
public static HttpURLConnection doRequest(String endpoint, CypherSession session, String[] keys, String[] values) throws IOException { HttpURLConnection connection = (java.net.HttpURLConnection) new URL(DOMAIN + endpoint).openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); connection.connect();/*from w ww. j a va 2 s . co m*/ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); if (session != null) { writer.write("userID="); writer.write(session.getUser().getUserID() + "&sessionID="); writer.write(session.getSessionID()); } if (keys != null && keys.length > 0) { if (session != null) { writer.write('&'); } // write first row writer.write(keys[0]); writer.write('='); writer.write(URLEncoder.encode(values[0], "UTF-8")); for (int i = 1; i < keys.length; i++) { writer.write('&'); writer.write(keys[i]); writer.write('='); writer.write(URLEncoder.encode(values[i], "UTF-8")); } } writer.close(); return connection; }
From source file:common.net.volley.toolbox.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { // before preConnect byte[] body = request.getBody(); if (body != null) { stethoManager.preConnect(connection, new ByteArrayRequestEntity(request.getBody())); connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body);// w ww . j a v a 2 s . co m out.close(); } }
From source file:com.wx.kernel.util.HttpKit.java
private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { URL _url = new URL(url); HttpURLConnection conn = (HttpURLConnection) _url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier); }/* www . ja v a 2s .c o m*/ conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(19000); conn.setReadTimeout(19000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (headers != null && !headers.isEmpty()) for (Entry<String, String> entry : headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); return conn; }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?url//from ww w .j av a2 s . c o m * * @param inputStream ? * @param fileName ?? * @param fileType * @param contentType * @param identity * @return */ public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName, String fileType, String contentType, String identity) { String lineEnd = System.getProperty("line.separator"); String twoHyphens = "--"; String boundary = "*****"; String result = null; try { //? URL submit = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) submit.openConnection(); // conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); //? conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", DEFAULT_CHARSET); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //?? DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + ";Content-Type=\"" + contentType + lineEnd); dos.writeBytes(lineEnd); byte[] buffer = new byte[8192]; // 8k int count = 0; while ((count = inputStream.read(buffer)) != -1) { dos.write(buffer, 0, count); } inputStream.close(); //? dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET); BufferedReader br = new BufferedReader(isr); result = br.readLine(); dos.close(); is.close(); } catch (IOException e) { logger.error("", e); } return result; }
From source file:LNISmokeTest.java
/** * Implement WebDAV PUT http request./*from w w w . java 2s.c om*/ * * 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: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); 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);//www.j a v a 2 s .c o m } rd.close(); } // res = URLDecoder.decode(res, "UTF-8"); return StringEscapeUtils.unescapeHtml(res.toString().replace("&lt", "<")); }