List of usage examples for java.net HttpURLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:com.reactivetechnologies.jaxrs.RestServerTest.java
static String sendDelete(String url, String content) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;/*from w ww.ja v a 2 s .c o m*/ try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("DELETE"); //add request header con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeUTF(content); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } } else { throw new IOException("Response Code: " + responseCode); } return response.toString(); } catch (IOException e) { throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); } } }
From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java
public static InputStream postConnection(Context context, URL url, String method, String urlParameters) throws IOException { if (!url.getProtocol().startsWith("http")) { return url.openStream(); }/*ww w. j av a 2s.c o m*/ URLConnection c = url.openConnection(); HttpURLConnection connection = (HttpURLConnection) c; connection.setRequestMethod(method.toUpperCase()); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); OutputStream output = null; try { output = connection.getOutputStream(); output.write(urlParameters.getBytes("UTF-8")); output.flush(); } finally { IOUtils.close(output); } return connection.getInputStream(); }
From source file:yodlee.ysl.api.io.HTTP.java
public static String doPostUser(String url, Map<String, String> sessionTokens, String requestBody, boolean isEncodingNeeded) throws IOException { String mn = "doIO(POST : " + url + ", " + requestBody + "sessionTokens : " + sessionTokens + " )"; System.out.println(fqcn + " :: " + mn); URL restURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) restURL.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("User-Agent", userAgent); if (isEncodingNeeded) //conn.setRequestProperty("Content-Type", contentTypeURLENCODED); conn.setRequestProperty("Content-Type", contentTypeJSON); else// w w w . ja va 2 s. com conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8"); conn.setRequestProperty("Authorization", sessionTokens.toString()); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(requestBody); wr.flush(); wr.close(); int responseCode = conn.getResponseCode(); System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP POST' request"); System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuilder jsonResponse = new StringBuilder(); while ((inputLine = in.readLine()) != null) { jsonResponse.append(inputLine); } in.close(); System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString()); return new String(jsonResponse); }
From source file:net.mceoin.cominghome.api.NestUtil.java
/** * Make HTTP/JSON call to Nest and set away status. * * @param access_token OAuth token to allow access to Nest * @param structure_id ID of structure with thermostat * @param away_status Either "home" or "away" * @return Equal to "Success" if successful, otherwise it contains a hint on the error. */// w w w . j a v a2 s.c om public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) { String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try { URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); String payload = "\"" + away_status + "\""; OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); log.info(payload); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); urlConnection.setRequestProperty("Accept", "application/json"); // System.out.println("Redirect to URL : " + newUrl); wr = new OutputStreamWriter(urlConnection.getOutputStream()); wr.write(payload); wr.flush(); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) { return "Error: " + errorResult; } else { return "Success"; } }
From source file:net.mceoin.cominghome.api.NestUtil.java
private static String getNestAwayStatusCall(String access_token) { String away_status = ""; String urlString = "https://developer-api.nest.com/structures?auth=" + access_token; log.info("url=" + urlString); StringBuilder builder = new StringBuilder(); boolean error = false; String errorResult = ""; HttpURLConnection urlConnection = null; try {//from ww w .j a v a2 s .co m URL url = new URL(urlString); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0"); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.setConnectTimeout(15000); urlConnection.setReadTimeout(15000); // urlConnection.setChunkedStreamingMode(0); // urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8"); boolean redirect = false; // normally, 3xx is redirect int status = urlConnection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 // Temporary redirect || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } // System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = urlConnection.getHeaderField("Location"); // open the new connnection again urlConnection = (HttpURLConnection) new URL(newUrl).openConnection(); urlConnection.setRequestMethod("PUT"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); // urlConnection.setChunkedStreamingMode(0); // System.out.println("Redirect to URL : " + newUrl); } int statusCode = urlConnection.getResponseCode(); log.info("statusCode=" + statusCode); if ((statusCode == HttpURLConnection.HTTP_OK)) { error = false; InputStream response; response = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); JSONObject structure = object.getJSONObject(key); if (structure.has("away")) { away_status = structure.getString("away"); } else { log.info("missing away"); } } } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { // bad auth error = true; errorResult = "Unauthorized"; } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) { error = true; InputStream response; response = urlConnection.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(response)); String line; while ((line = reader.readLine()) != null) { builder.append(line); } log.info("response=" + builder.toString()); JSONObject object = new JSONObject(builder.toString()); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); if (key.equals("error")) { // error = Internal Error on bad structure_id errorResult = object.getString("error"); log.info("errorResult=" + errorResult); } } } else { error = true; errorResult = Integer.toString(statusCode); } } catch (IOException e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("IOException: " + errorResult); } catch (Exception e) { error = true; errorResult = e.getLocalizedMessage(); log.warning("Exception: " + errorResult); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (error) away_status = "Error: " + errorResult; return away_status; }
From source file:com.jooketechnologies.network.ServerUtilities.java
static JSONObject post(String endpoint, int action, Map<String, String> params) { URL url;/*from ww w . java 2 s .c o m*/ try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=').append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); InputStream is = conn.getInputStream(); if (status != 200) { if (conn != null) { conn.disconnect(); } } else { JSONObject jsonObject = streamToString(is); return jsonObject; } } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.gmt2001.HttpRequest.java
public static HttpResponse getData(RequestType type, String url, String post, HashMap<String, String> headers) { Thread.setDefaultUncaughtExceptionHandler(com.gmt2001.UncaughtExceptionHandler.instance()); HttpResponse r = new HttpResponse(); r.type = type;// w w w. ja va 2 s . c o m r.url = url; r.post = post; r.headers = headers; try { URL u = new URL(url); HttpURLConnection h = (HttpURLConnection) u.openConnection(); for (Entry<String, String> e : headers.entrySet()) { h.addRequestProperty(e.getKey(), e.getValue()); } h.setRequestMethod(type.name()); h.setUseCaches(false); h.setDefaultUseCaches(false); h.setConnectTimeout(timeout); h.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 PhantomBotJ/2015"); if (!post.isEmpty()) { h.setDoOutput(true); } h.connect(); if (!post.isEmpty()) { BufferedOutputStream stream = new BufferedOutputStream(h.getOutputStream()); stream.write(post.getBytes()); stream.flush(); stream.close(); } if (h.getResponseCode() < 400) { r.content = IOUtils.toString(new BufferedInputStream(h.getInputStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = true; } else { r.content = IOUtils.toString(new BufferedInputStream(h.getErrorStream()), h.getContentEncoding()); r.httpCode = h.getResponseCode(); r.success = false; } } catch (IOException ex) { r.success = false; r.httpCode = 0; r.exception = ex.getMessage(); com.gmt2001.Console.err.printStackTrace(ex); } return r; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a string via POST to a given url. * * @param context the context to use. * @param urlStr the url to which to send to. * @param string the string to send as post body. * @param user the user or <code>null</code>. * @param password the password or <code>null</code>. * @param readResponse if <code>true</code>, the response from the server is read and parsed as return message. * @return the response.//from ww w. ja v a 2 s . com * @throws Exception if something goes wrong. */ public static String sendPost(Context context, String urlStr, String string, String user, String password, boolean readResponse) throws Exception { BufferedOutputStream wr = null; HttpURLConnection conn = null; try { conn = makeNewConnection(urlStr); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // conn.setChunkedStreamingMode(0); conn.setUseCaches(false); if (user != null && password != null && user.trim().length() > 0 && password.trim().length() > 0) { conn.setRequestProperty("Authorization", getB64Auth(user, password)); } conn.connect(); // Make server believe we are form data... wr = new BufferedOutputStream(conn.getOutputStream()); byte[] bytes = string.getBytes(); wr.write(bytes); wr.flush(); int responseCode = conn.getResponseCode(); if (readResponse) { StringBuilder returnMessageBuilder = new StringBuilder(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); while (true) { String line = br.readLine(); if (line == null) break; returnMessageBuilder.append(line + "\n"); } br.close(); } return returnMessageBuilder.toString(); } else { return getMessageForCode(context, responseCode, context.getResources().getString(R.string.post_completed_properly)); } } catch (Exception e) { throw e; } finally { if (conn != null) conn.disconnect(); } }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? ? /*from w ww. j av a 2 s . com*/ * @param access_token ?? * @param msgType image?voice?videothumb * @param localFile * @return */ @Deprecated public static String uploadMedia(String access_token, String msgType, String localFile) { String media_id = null; String url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=" + access_token + "&type=" + msgType; 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); // con.setRequestProperty("Content-Type", // "multipart/mixed; boundary=" + BOUNDARY); // con.setRequestProperty("content-type", "text/html"); // ? // 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:com.createtank.payments.coinbase.RequestClient.java
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry, String accessToken) throws IOException, UnsupportedRequestVerbException { if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) { throw new UnsupportedRequestVerbException(); }//from w ww .jav a 2s .c om if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request; switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } ((HttpEntityEnclosingRequestBase) request) .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON)); if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); request.addHeader("Content-Type", "application/json"); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = EntityUtils.toString(response.getEntity()); if (responseString.startsWith("[")) { // Is an array responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(responseString); System.out.println(resp.toString()); return resp; } String url = BASE_URL + method; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); conn.addRequestProperty("Content-Type", "application/json"); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(json.toString()); writer.flush(); writer.close(); int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, json, false, api.getAccessToken()); } else { throw new IOException("Account is no longer valid"); } } else if (code != 200) { throw new IOException("HTTP response " + code + " to request " + method); } String responseString = getResponseBody(conn.getInputStream()); if (responseString.startsWith("[")) { responseString = "{response:" + responseString + "}"; } JsonParser parser = new JsonParser(); return (JsonObject) parser.parse(responseString); }