List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.cloudbees.mtslaves.client.RemoteReference.java
protected HttpURLConnection postJson(HttpURLConnection con, JSONObject json) throws IOException { try {/* w w w . j a va2s . co m*/ token.authorizeRequest(con); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); con.connect(); // send JSON OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8"); json.write(w); w.close(); return con; } catch (IOException e) { throw (IOException) new IOException("Failed to POST to " + url).initCause(e); } }
From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that needs to be handled for backwards // compatibility. // If the request's post body is null, then the assumption is that // the request is // GET. Otherwise, it is assumed that the request is a POST. byte[] postBody = request.getPostBody(); if (postBody != null) { // Prepare output. There is no need to set Content-Length // explicitly, // since this is handled by HttpURLConnection using the size of // the prepared // output stream. connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(postBody);/*from w ww . j a v a 2 s .co m*/ out.close(); } break; case Method.GET: // Not necessary to set the request method because connection // defaults to GET but // being explicit here. connection.setRequestMethod("GET"); break; case Method.DELETE: connection.setRequestMethod("DELETE"); break; case Method.POST: connection.setRequestMethod("POST"); addBodyIfExists(connection, request); break; case Method.PUT: connection.setRequestMethod("PUT"); addBodyIfExists(connection, request); break; case Method.HEAD: connection.setRequestMethod("HEAD"); break; case Method.OPTIONS: connection.setRequestMethod("OPTIONS"); break; case Method.TRACE: connection.setRequestMethod("TRACE"); break; case Method.PATCH: // connection.setRequestMethod("PATCH"); // If server doesnt support patch uncomment this connection.setRequestMethod("POST"); connection.setRequestProperty("X-HTTP-Method-Override", "PATCH"); addBodyIfExists(connection, request); break; default: throw new IllegalStateException("Unknown method type."); } }
From source file:com.ibm.stocator.fs.swift.auth.PasswordScopeAccessProvider.java
/** * Authentication logic/* w w w . java 2 s . co m*/ * * @return Access JOSS access object * @throws IOException if failed to parse the response */ public Access passwordScopeAuth() throws IOException { InputStreamReader reader = null; BufferedReader bufReader = null; try { JSONObject user = new JSONObject(); user.put("id", mUserId); user.put("password", mPassword); JSONObject password = new JSONObject(); password.put("user", user); JSONArray methods = new JSONArray(); methods.add("password"); JSONObject identity = new JSONObject(); identity.put("methods", methods); identity.put("password", password); JSONObject project = new JSONObject(); project.put("id", mProjectId); JSONObject scope = new JSONObject(); scope.put("project", project); JSONObject auth = new JSONObject(); auth.put("identity", identity); auth.put("scope", scope); JSONObject requestBody = new JSONObject(); requestBody.put("auth", auth); HttpURLConnection connection = (HttpURLConnection) new URL(mAuthUrl).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/json"); OutputStream output = connection.getOutputStream(); output.write(requestBody.toString().getBytes()); int status = connection.getResponseCode(); if (status != 201) { return null; } reader = new InputStreamReader(connection.getInputStream()); bufReader = new BufferedReader(reader); String res = bufReader.readLine(); JSONParser parser = new JSONParser(); JSONObject jsonResponse = (JSONObject) parser.parse(res); String token = connection.getHeaderField("X-Subject-Token"); PasswordScopeAccess access = new PasswordScopeAccess(jsonResponse, token, mPrefferedRegion); bufReader.close(); reader.close(); connection.disconnect(); return access; } catch (Exception e) { if (bufReader != null) { bufReader.close(); } if (reader != null) { reader.close(); } throw new IOException(e); } }
From source file:com.example.gaefirebaseeventproxy.FirebaseEventProxy.java
public void start() { DatabaseReference firebase = FirebaseDatabase.getInstance().getReference(); // Subscribe to value events. Depending on use case, you may want to subscribe to child events // through childEventListener. firebase.addValueEventListener(new ValueEventListener() { @Override/*from w w w.j av a 2 s.c o m*/ public void onDataChange(DataSnapshot snapshot) { if (snapshot.exists()) { try { // Convert value to JSON using Jackson String json = new ObjectMapper().writeValueAsString(snapshot.getValue(false)); // Replace the URL with the url of your own listener app. URL dest = new URL("http://gae-firebase-listener-python.appspot.com/log"); HttpURLConnection connection = (HttpURLConnection) dest.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); // Rely on X-Appengine-Inbound-Appid to authenticate. Turning off redirects is // required to enable. connection.setInstanceFollowRedirects(false); // Fill out header if in dev environment if (SystemProperty.environment.value() != SystemProperty.Environment.Value.Production) { connection.setRequestProperty("X-Appengine-Inbound-Appid", "dev-instance"); } // Put Firebase data into http request StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("&fbSnapshot="); stringBuilder.append(URLEncoder.encode(json, "UTF-8")); connection.getOutputStream().write(stringBuilder.toString().getBytes()); if (connection.getResponseCode() != 200) { log.severe("Forwarding failed"); } else { log.info("Sent: " + json); } } catch (JsonProcessingException e) { log.severe("Unable to convert Firebase response to JSON: " + e.getMessage()); } catch (IOException e) { log.severe("Error in connecting to app engine: " + e.getMessage()); } } } @Override public void onCancelled(DatabaseError error) { log.severe("Firebase connection cancelled: " + error.getMessage()); } }); }
From source file:com.PAB.ibeaconreference.AppEngineSpatial.java
public static Response getOrPost(Request request) { mErrorMessage = null;/*from w w w . j av a2 s . com*/ HttpURLConnection conn = null; Response response = null; try { conn = (HttpURLConnection) request.uri.openConnection(); // if (!mAuthenticator.authenticate(conn)) { // mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage(); // } else { if (request.headers != null) { for (String header : request.headers.keySet()) { for (String value : request.headers.get(header)) { conn.addRequestProperty(header, value); } } } if (request instanceof PUT) { byte[] payload = ((PUT) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("PUT"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); } if (request instanceof POST) { byte[] payload = ((POST) request).body; String s = new String(payload, "UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); JSONObject jsonobj = getJSONObject(s); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); OutputStream os = conn.getOutputStream(); os.write(jsonobj.toString().getBytes("UTF-8")); os.close(); // conn.setFixedLengthStreamingMode(payload.length); // conn.getOutputStream().write(payload); int status = conn.getResponseCode(); if (status / 100 != 2) response = new Response(status, new Hashtable<String, List<String>>(), conn.getResponseMessage().getBytes()); } if (response == null) { int a = conn.getResponseCode(); if (a == 401) { response = new Response(a, conn.getHeaderFields(), new byte[] {}); } InputStream a1 = conn.getErrorStream(); BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); byte[] body = readStream(in); a12 = new String(body, "US-ASCII"); response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body); // List<String> a = conn.getHeaderFields().get("aa"); } } } catch (IOException e) { e.printStackTrace(System.err); } finally { if (conn != null) conn.disconnect(); } return response; }
From source file:de.thingweb.discovery.TDRepository.java
/** * Deletes repository by using key/*from w ww. ja va 2 s. c o m*/ * * @param key in repository (/td/{id}) * @throws Exception in case of error */ public void deleteTD(String key) throws Exception { URL url = new URL("http://" + repository_uri + key); HttpURLConnection httpCon = (HttpURLConnection) url.openConnection(); httpCon.setDoOutput(true); httpCon.setRequestProperty("content-type", "application/ld+json"); httpCon.setRequestMethod("DELETE"); // httpCon.connect(); int responseCode = httpCon.getResponseCode(); if (responseCode != 200) { // error throw new RuntimeException("ResponseCodeError: " + responseCode); } }
From source file:com.synapticpath.pisecure.modules.LogglyEventLoggerModule.java
private void logEvent(SystemEvent event) { try {//from w w w. j a va2s . c om byte[] postData = event.toJson().getBytes(StandardCharsets.UTF_8); int postDataLength = postData.length; URL url = new URL(String.format(postRequestUrl, token, tag)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setInstanceFollowRedirects(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Length", Integer.toString(postDataLength)); conn.setUseCaches(false); try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) { wr.write(postData); } if (conn.getResponseCode() == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder response = new StringBuilder(); String inputLine = null; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:dk.clarin.tools.workflow.java
/** * Sends an HTTP GET request to a url/*from ww w .j av a2s . c o m*/ * * @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search") * @param requestString - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself * @return - The response from the end point */ public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat, String filename, String jobID, boolean postmethod) { int code = 0; String message = ""; //String filelist; if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) { // Send a GET or POST request to the servlet try { // Construct data String requestResult = ""; String urlStr = endpoint; if (postmethod) // HTTP POST { logger.debug("HTTP POST"); StringReader input = new StringReader(requestString); StringWriter output = new StringWriter(); URL endp = new URL(endpoint); HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) endp.openConnection(); 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", "text/xml; charset=" + "UTF-8"); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(input, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) out.close(); } } catch (IOException e) { throw new Exception("Connection error (is server running at " + endp + " ?): " + e); } finally { if (urlc != null) { code = urlc.getResponseCode(); if (code == 200) { got200(result, BracMat, filename, jobID, urlc.getInputStream()); } else { InputStream in = urlc.getInputStream(); try { Reader reader = new InputStreamReader(in); pipe(reader, output); reader.close(); requestResult = output.toString(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) in.close(); } logger.debug("urlc.getResponseCode() == {}", code); message = urlc.getResponseMessage(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } urlc.disconnect(); } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } //requestResult = output.toString(); logger.debug("postData returns " + requestResult); } else // HTTP GET { logger.debug("HTTP GET"); // Send data if (requestString != null && requestString.length() > 0) { urlStr += "?" + requestString; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); conn.connect(); // Cast to a HttpURLConnection if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); logger.debug("httpConnection.getResponseCode() == {}", code); message = httpConnection.getResponseMessage(); BufferedReader rd; StringBuilder sb = new StringBuilder(); ; //String line; if (code == 200) { got200(result, BracMat, filename, jobID, httpConnection.getInputStream()); } else { // Get the error response rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream())); int nextChar; while ((nextChar = rd.read()) != -1) { sb.append((char) nextChar); } rd.close(); requestResult = sb.toString(); didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } else { code = 0; didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod, urlStr, message, requestResult); } } logger.debug("Job " + jobID + " receives status code [" + code + "] from tool."); } catch (Exception e) { //jobs = 0; // No more jobs to process now, probably the tool is not reachable logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage()); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } } else { //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint + ")"); /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")"); } return code; }
From source file:hudson.plugins.memegen.MemegeneratorResponseException.java
public boolean instanceCreate(Meme meme) { boolean ret = false; HashMap<String, String> vars = new HashMap(); vars.put("username", username); vars.put("password", password); vars.put("text0", meme.getUpperText()); vars.put("text1", meme.getLowerText()); vars.put("generatorID", "" + meme.getGeneratorID()); vars.put("imageID", "" + meme.getImageID()); try {// w w w . j a v a 2s . c o m URL url = buildURL("Instance_Create", vars); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); conn.setDoOutput(true); JSONObject obj = parseResponse(conn); JSONObject result = (JSONObject) obj.get("result"); String memeUrl = (String) result.get("instanceImageUrl"); if (memeUrl.matches("^http(.*)") == false) { memeUrl = APIURL + memeUrl; } //Debug the JSON to logs //System.err.println(obj.toJSONString()+", AND "+result.toJSONString()); meme.setImageURL(memeUrl); ret = true; } catch (MalformedURLException me) { String log_warn_prefix = "Memegenerator API malformed URL: "; System.err.println(log_warn_prefix.concat(me.getMessage())); } catch (IOException ie) { String log_warn_prefix = "Memegenerator API IO exception: "; System.err.println(log_warn_prefix.concat(ie.getMessage())); } catch (ParseException pe) { String log_warn_prefix = "Memegenerator API malformed response: "; System.err.println(log_warn_prefix.concat(pe.getMessage())); } catch (MemegeneratorResponseException mre) { String log_warn_prefix = "Memegenerator API failure: "; System.err.println(log_warn_prefix.concat(mre.getMessage())); } catch (MemegeneratorJSONException mje) { String log_warn_prefix = "Memegenerator API malformed JSON: "; System.err.println(log_warn_prefix.concat(mje.getMessage())); } return ret; }
From source file:com.spotify.helios.system.APITest.java
private HttpURLConnection post(final String path, final byte[] body) throws IOException { final URL url = new URL(masterEndpoint() + path); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setDoInput(true);//www. j av a 2 s . co m connection.setDoOutput(true); connection.getOutputStream().write(body); return connection; }