List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:com.iStudy.Study.Renren.Util.java
/** * ??http/*from www . ja v a 2s . c o m*/ * * @param url * @param method GET POST * @param params * @return */ public static String openUrl(String url, String method, Bundle params) { if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } String response = ""; try { Log.d(LOG_TAG, method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", USER_AGENT_SDK); if (!method.equals("GET")) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.getOutputStream().write(encodeUrl(params).getBytes("UTF-8")); } InputStream is = null; int responseCode = conn.getResponseCode(); if (responseCode == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); } response = read(is); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } return response; }
From source file:Main.java
public static String getPosthtml(String posturl, String postData, String encode) { String html = ""; URL url;/* w w w .ja v a 2 s . c o m*/ try { url = new URL(posturl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("User-Agent", userAgent); String postDataStr = postData; byte[] bytes = postDataStr.getBytes("utf-8"); connection.setRequestProperty("Content-Length", "" + bytes.length); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Cache-Control", "no-cache"); connection.setDoOutput(true); connection.setReadTimeout(timeout); connection.setFollowRedirects(true); connection.connect(); OutputStream outStrm = connection.getOutputStream(); outStrm.write(bytes); outStrm.flush(); outStrm.close(); InputStream inStrm = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inStrm, encode)); String temp = ""; while ((temp = br.readLine()) != null) { html += (temp + '\n'); } br.close(); connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } return html; }
From source file:com.arellomobile.android.push.utils.NetworkUtils.java
public static NetworkResult makeRequest(Map<String, Object> data, String methodName) throws Exception { NetworkResult result = new NetworkResult(500, null); OutputStream connectionOutput = null; InputStream inputStream = null; try {/*ww w .j a v a 2 s . com*/ String urlString = NetworkUtils.BASE_URL + methodName; if (useSSL) urlString = NetworkUtils.BASE_URL_SECURE + methodName; URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); connection.setDoOutput(true); JSONObject innerRequestJson = new JSONObject(); for (String key : data.keySet()) { innerRequestJson.put(key, data.get(key)); } JSONObject requestJson = new JSONObject(); requestJson.put("request", innerRequestJson); connection.setRequestProperty("Content-Length", String.valueOf(requestJson.toString().getBytes().length)); connectionOutput = connection.getOutputStream(); connectionOutput.write(requestJson.toString().getBytes()); connectionOutput.flush(); connectionOutput.close(); inputStream = new BufferedInputStream(connection.getInputStream()); ByteArrayOutputStream dataCache = new ByteArrayOutputStream(); // Fully read data byte[] buff = new byte[1024]; int len; while ((len = inputStream.read(buff)) >= 0) { dataCache.write(buff, 0, len); } // Close streams dataCache.close(); String jsonString = new String(dataCache.toByteArray()).trim(); Log.w(TAG, "PushWooshResult: " + jsonString); JSONObject resultJSON = new JSONObject(jsonString); result.setData(resultJSON); result.setCode(resultJSON.getInt("status_code")); } finally { if (null != inputStream) { inputStream.close(); } if (null != connectionOutput) { connectionOutput.close(); } } return result; }
From source file:com.android.volley.toolbox.http.HurlStack.java
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { if (request.containsFile()) { setConnectionParametersForMultipartRequest(connection, request); } else {// w w w . j av a 2 s .co m byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
private static HttpURLConnection makePostConnection(URL url, byte[] bytes) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);//from ww w .j a v a 2 s . c o m conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // Add in API key String authKey = new String(Base64.encodeBase64((key + ":").getBytes())); conn.setRequestProperty("Authorization", "Basic " + authKey); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); return conn; }
From source file:disko.DU.java
public static String request(String targetUrl, String method, String text, String contentType) throws Exception { URL url = new URL(targetUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (method != null) conn.setRequestMethod(method);//from ww w.j av a2s . c o m if (contentType != null) conn.setRequestProperty("Content-Type", contentType); if (text != null) { conn.setDoOutput(true); conn.setUseCaches(false); conn.getOutputStream().write(text.getBytes()); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.write(text.getBytes()); out.flush(); out.close(); } if (conn.getResponseCode() != 200) throw new RuntimeException("HTTPClient failed: " + conn.getResponseCode()); StringBuffer responseBuffer = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String eol = new String(new byte[] { 13 }); while ((line = in.readLine()) != null) { responseBuffer.append(line); responseBuffer.append(eol); } in.close(); return responseBuffer.toString(); }
From source file:com.createtank.payments.coinbase.RequestClient.java
private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params, boolean retry, String accessToken) throws IOException { if (api.allowSecure()) { HttpClient client = HttpClientBuilder.create().build(); String url = BASE_URL + method; HttpUriRequest request = null;/* w w w . ja va 2 s . co m*/ if (verb == RequestVerb.POST || verb == RequestVerb.PUT) { switch (verb) { case POST: request = new HttpPost(url); break; case PUT: request = new HttpPut(url); break; default: throw new RuntimeException("RequestVerb not implemented: " + verb); } List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>(); if (params != null) { List<BasicNameValuePair> convertedParams = convertParams(params); paramsBody.addAll(convertedParams); } ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8")); } else { if (params != null) { url = url + "?" + createRequestParams(params); } if (verb == RequestVerb.GET) { request = new HttpGet(url); } else if (verb == RequestVerb.DELETE) { request = new HttpDelete(url); } } if (request == null) return null; if (accessToken != null) request.addHeader("Authorization", String.format("Bearer %s", accessToken)); System.out.println("auth header: " + request.getFirstHeader("Authorization")); HttpResponse response = client.execute(request); int code = response.getStatusLine().getStatusCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); call(api, method, verb, params, 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 paramStr = createRequestParams(params); String url = BASE_URL + method; if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE) url += "?" + paramStr; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(verb.name()); if (accessToken != null) conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken)); if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) { conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(paramStr); writer.flush(); writer.close(); } int code = conn.getResponseCode(); if (code == 401) { if (retry) { api.refreshAccessToken(); return call(api, method, verb, params, 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); }
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.j av a2 s.c om 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:lapispaste.Main.java
private static void paster(Map<String, String> pastemap, StringBuffer pdata) { try {/* ww w .j a va2s . com*/ URL url = new URL("http://paste.linux-sevenler.org/index.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // set connection 'writeable' conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); // construct the data... String data; String pdataString = pdata.toString(); data = URLEncoder.encode("language", "ISO-8859-9") + "=" + URLEncoder.encode(pastemap.get("format"), "ISO-8859-9"); data += "&" + URLEncoder.encode("source", "ISO-8859-9") + "=" + URLEncoder.encode(pdataString, "ISO-8859-9"); data += "&" + URLEncoder.encode("submit", "ISO-8859-9") + "=" + URLEncoder.encode(" Kaydet ", "ISO-8859-9"); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); // get new url where the paste is conn.getInputStream(); System.out.println(conn.getURL()); conn.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } }
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 .j a va 2 s .c om 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(); } }