List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:com.reactivetechnologies.jaxrs.RestServerTest.java
static String sendPost(String url, String content) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;// www.j a v a2 s. com try { URL obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("POST"); //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.reactivetechnologies.jaxrs.RestServerTest.java
static String sendDelete(String url, String content) throws IOException { StringBuilder response = new StringBuilder(); HttpURLConnection con = null; BufferedReader in = null;/* w ww.j av a2 s. co 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.illusionaryone.FrankerZAPIv1.java
@SuppressWarnings("UseSpecificCatch") private static JSONObject readJsonFromUrl(String urlAddress) { JSONObject jsonResult = new JSONObject("{}"); InputStream inputStream = null; URL urlRaw;/*from ww w .j av a2 s .com*/ HttpURLConnection urlConn; String jsonText = ""; try { urlRaw = new URL(urlAddress); urlConn = (HttpURLConnection) urlRaw.openConnection(); urlConn.setDoInput(true); urlConn.setRequestMethod("GET"); urlConn.addRequestProperty("Content-Type", "application/json"); urlConn.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"); urlConn.connect(); if (urlConn.getResponseCode() == 200) { inputStream = urlConn.getInputStream(); } else { inputStream = urlConn.getErrorStream(); } BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); jsonText = readAll(rd); jsonResult = new JSONObject(jsonText); fillJSONObject(jsonResult, true, "GET", urlAddress, urlConn.getResponseCode(), "", "", jsonText); } catch (JSONException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "JSONException", ex.getMessage(), jsonText); com.gmt2001.Console.err.printStackTrace(ex); } catch (NullPointerException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "NullPointerException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (MalformedURLException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "MalformedURLException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (SocketTimeoutException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "SocketTimeoutException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } catch (Exception ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "Exception", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } finally { if (inputStream != null) try { inputStream.close(); } catch (IOException ex) { fillJSONObject(jsonResult, false, "GET", urlAddress, 0, "IOException", ex.getMessage(), ""); com.gmt2001.Console.err.printStackTrace(ex); } } return (jsonResult); }
From source file:com.openforevent.main.UserPosition.java
public static Map<String, Object> userLocationProperties(DispatchContext ctx, Map<String, ? extends Object> context) throws IOException { Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); String visitId = (String) context.get("visitId"); if (Debug.infoOn()) { Debug.logInfo("In userLocationProperties", module); }/* w ww . ja v a2 s .c o m*/ // get user coords coordsOfUserPosition(ctx, context); URL url = new URL( "https://graph.facebook.com/search?since=now&limit=4&q=2012-05-07&type=event&access_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode = urlConnection.getResponseCode(); InputStream inputStream; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream = urlConnection.getInputStream(); } else { inputStream = urlConnection.getErrorStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(inputStream, writer, "UTF-8"); String theString = writer.toString(); Debug.logInfo("Facebook stream = ", theString); if (theString.contains("AuthException") == true) { url = new URL("https://graph.facebook.com/oauth/access_token?" + "client_id= 283576871735609&" + "client_secret= 5cf1fe4e531dff8de228bfac61b8fdfa&" + "grant_type=fb_exchange_token&" + "fb_exchange_token=" + "AAACEdEose0cBAN9CB2ErxVN3JvK2gsrLslPt6e6Y7hJ0OrMEkMoyNwvHgSZCAEu2lCHZALlVWXZCW5JL8asMWoaPN3UAXFpZBsJJ6SvXRAAIZAXeTo0fD"); HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection(); // Set properties of the connection urlConnection1.setRequestMethod("GET"); urlConnection1.setDoInput(true); urlConnection1.setDoOutput(true); urlConnection1.setUseCaches(false); urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // Retrieve the output int responseCode1 = urlConnection1.getResponseCode(); InputStream inputStream1; if (responseCode == HttpURLConnection.HTTP_OK) { inputStream1 = urlConnection1.getInputStream(); } else { inputStream1 = urlConnection1.getErrorStream(); } StringWriter writer1 = new StringWriter(); IOUtils.copy(inputStream1, writer1, "UTF-8"); String theString1 = writer1.toString(); Debug.logInfo("Facebook stream1 = ", theString1); } Map<String, Object> paramOut = FastMap.newInstance(); paramOut.put("geoName", "aaa"); paramOut.put("abbreviation", "bbb"); return paramOut; }
From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java
/** * send a HTTP POST request//from w w w . j a v a 2s . c om * @param param * @param input_url * @return */ public static String POST(String param, String input_url) { try { URL url = new URL(input_url); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/xml"); con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); PrintWriter xmlOut = new PrintWriter(con.getOutputStream()); xmlOut.write(param); xmlOut.flush(); BufferedReader response = new BufferedReader(new InputStreamReader(con.getInputStream())); String result = ""; String line; while ((line = response.readLine()) != null) { result += "\n" + line; } return result.toString(); } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:edu.dartmouth.cs.dartcard.HttpUtilities.java
private static HttpURLConnection makeGetConnection(URL url, byte[] bytes) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);/*from ww w .j av a2 s . c o m*/ conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); return conn; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
public static HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " OCCAndroidSDK"); return connection; }
From source file:export.FormCrawler.java
public static void postMulti(HttpURLConnection conn, Part<?> parts[]) throws IOException { String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream()); for (int i = 0; i < parts.length; i++) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + parts[i].name + "\""); if (parts[i].filename != null) outputStream.writeBytes("; filename=\"" + parts[i].filename + "\""); outputStream.writeBytes(lineEnd); if (parts[i].contentType != null) outputStream.writeBytes("Content-Type: " + parts[i].contentType + lineEnd); if (parts[i].contentTransferEncoding != null) outputStream.writeBytes("Content-Transfer-Encoding: " + parts[i].contentTransferEncoding + lineEnd); outputStream.writeBytes(lineEnd); parts[i].value.write(outputStream); outputStream.writeBytes(lineEnd); }/*from ww w.j a va 2 s .c om*/ outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); outputStream.flush(); outputStream.close(); }
From source file:com.googlecode.osde.internal.igoogle.IgCredentials.java
/** * Makes a HTTP POST request for authentication. * * @param emailUserName the name of the user * @param password the password of the user * @param loginTokenOfCaptcha CAPTCHA token (Optional) * @param loginCaptchaAnswer answer of CAPTCHA token (Optional) * @return http response as a String//from w w w .j a v a2s.c o m * @throws IOException */ // TODO: Refactor requestAuthentication() utilizing HttpPost. private static String requestAuthentication(String emailUserName, String password, String loginTokenOfCaptcha, String loginCaptchaAnswer) throws IOException { // Prepare connection. URL url = new URL(URL_GOOGLE_LOGIN); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); logger.fine("url: " + url); // Form the POST params. StringBuilder params = new StringBuilder(); params.append("Email=").append(emailUserName).append("&Passwd=").append(password) .append("&source=OSDE-01&service=ig&accountType=HOSTED_OR_GOOGLE"); if (loginTokenOfCaptcha != null) { params.append("&logintoken=").append(loginTokenOfCaptcha); } if (loginCaptchaAnswer != null) { params.append("&logincaptcha=").append(loginCaptchaAnswer); } // Send POST via output stream. OutputStream outputStream = null; try { outputStream = urlConnection.getOutputStream(); outputStream.write(params.toString().getBytes(IgHttpUtil.ENCODING)); outputStream.flush(); } finally { if (outputStream != null) { outputStream.close(); } } // Retrieve response. // TODO: Should the caller of this method need to know the responseCode? int responseCode = urlConnection.getResponseCode(); logger.fine("responseCode: " + responseCode); InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK) ? urlConnection.getInputStream() : urlConnection.getErrorStream(); logger.fine("inputStream: " + inputStream); try { String response = IOUtils.toString(inputStream, IgHttpUtil.ENCODING); return response; } finally { if (inputStream != null) { inputStream.close(); } } }
From source file:org.pixmob.fm2.util.HttpUtils.java
/** * Create a new Http connection for an URI. */// w ww . j a v a2 s. co m public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies) throws IOException { if (DEBUG) { Log.d(TAG, "Setup connection to " + uri); } final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection(); conn.setUseCaches(false); conn.setInstanceFollowRedirects(false); conn.setConnectTimeout(30000); conn.setReadTimeout(60000); conn.setRequestProperty("Accept-Encoding", "gzip"); conn.setRequestProperty("User-Agent", getUserAgent(context)); conn.setRequestProperty("Cache-Control", "max-age=0"); conn.setDoInput(true); // Close the connection when the request is done, or the application may // freeze due to a bug in some Android versions. conn.setRequestProperty("Connection", "close"); if (conn instanceof HttpsURLConnection) { setupSecureConnection(context, (HttpsURLConnection) conn); } if (cookies != null && !cookies.isEmpty()) { final StringBuilder buf = new StringBuilder(256); for (final String cookie : cookies) { if (buf.length() != 0) { buf.append("; "); } buf.append(cookie); } conn.addRequestProperty("Cookie", buf.toString()); } return conn; }