List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:Main.java
public static String getPosthtml(String posturl, String postData, String encode) { String html = ""; URL url;// w w w . j a v a 2s . 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:Main.java
public static void setUpConnection(HttpURLConnection connection, String method) { try {//from w w w . j a v a2 s . c om connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); } catch (ProtocolException e) { e.printStackTrace(); } }
From source file:Main.java
/** * Uses http to post an XML String to a URL. * * @param url/*w w w.j a va2 s .c om*/ * @param xmlString * @param return * @throws IOException * @throws UnknownHostException */ public static HttpURLConnection post(String url, String xmlString) throws IOException, UnknownHostException { // open connection URL urlObject = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); connection.setDoOutput(true); OutputStreamWriter outStream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); outStream.write(xmlString); outStream.close(); return connection; }
From source file:Main.java
public static String jsonGetRequest(String urlQueryString) { String json = null;/* w w w . jav a 2 s . co m*/ try { URL url = new URL(urlQueryString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.connect(); InputStream inStream = connection.getInputStream(); json = streamToString(inStream); // input stream to string } catch (IOException ex) { ex.printStackTrace(); } return json; }
From source file:com.francelabs.datafari.utils.SendHttpRequest.java
public static void sendGET(String url, String userAgent) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", userAgent); int responseCode = con.getResponseCode(); logger.debug("GET Response Code :: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { // success BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine;/* w w w. j a v a2s.com*/ StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // print result logger.debug(response.toString()); } else { logger.debug("GET request not worked"); } }
From source file:Authentication.DinserverAuth.java
public static boolean Login(String nick, String pass, Socket socket) throws IOException { boolean logged = false; JSONObject authRequest = new JSONObject(); authRequest.put("username", nick); authRequest.put("auth_id", pass); String query = "http://127.0.0.1:5000/token"; URL url = new URL(query); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000);// w w w . j av a 2s . c om conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream os = conn.getOutputStream(); os.write(authRequest.toString().getBytes(Charset.forName("UTF-8"))); os.close(); String output = new String(); StringBuilder sb = new StringBuilder(); int HttpResult = conn.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { output = IOUtils.toString(new InputStreamReader(conn.getInputStream(), Charset.forName("UTF-8"))); } else { System.out.println(conn.getResponseMessage()); } JSONObject jsonObject = new JSONObject(output); logged = jsonObject.getBoolean("ok"); conn.disconnect(); if (logged) { if (DinserverMaster.addUser(nick, socket)) { System.out.println("User " + nick + " logged in"); } else { logged = false; } } return logged; }
From source file:me.prokopyl.commandtools.migration.UUIDFetcher.java
private static HttpURLConnection createConnection() throws IOException { URL url = new URL(PROFILE_URL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false);//from w w w . jav a 2 s . c om connection.setDoInput(true); connection.setDoOutput(true); return connection; }
From source file:com.mopaas_mobile.http.BaseHttpRequester.java
public static String doGETwithHeader(String urlstr, String token, List<BasicNameValuePair> params) throws IOException { String result = null;//from w ww .j ava 2 s . c o m String content = ""; for (int i = 0; i < params.size(); i++) { content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8"); } URL url = new URL(urlstr + "?" + content.substring(1)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("token", token); connection.setDoInput(true); connection.setRequestMethod("GET"); connection.setUseCaches(false); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer b = new StringBuffer(); int ch; while ((ch = br.read()) != -1) { b.append((char) ch); } result = b.toString().trim(); connection.disconnect(); return result; }
From source file:com.fastbootmobile.encore.api.common.HttpGet.java
/** * Downloads the data from the provided URL. * @param inUrl The URL to get from/*w ww . java 2 s.com*/ * @param query The query field. '?' + query will be appended automatically, and the query data * MUST be encoded properly. * @return A byte array of the data */ public static byte[] getBytes(String inUrl, String query, boolean cached) throws IOException, RateLimitException { final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query)); Log.d(TAG, "Formatted URL: " + formattedUrl); URL url = new URL(formattedUrl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)"); urlConnection.setUseCaches(cached); urlConnection.setInstanceFollowRedirects(true); int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale); try { final int status = urlConnection.getResponseCode(); // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway. if (status == HttpURLConnection.HTTP_OK) { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); int contentLength = urlConnection.getContentLength(); if (contentLength <= 0) { // No length? Let's allocate 100KB. contentLength = 100 * 1024; } ByteArrayBuffer bab = new ByteArrayBuffer(contentLength); BufferedInputStream bis = new BufferedInputStream(in); int character; while ((character = bis.read()) != -1) { bab.append(character); } return bab.toByteArray(); } else if (status == HttpURLConnection.HTTP_NOT_FOUND) { // 404 return new byte[] {}; } else if (status == HttpURLConnection.HTTP_FORBIDDEN) { return new byte[] {}; } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) { throw new RateLimitException(); } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */ || status == HttpURLConnection.HTTP_SEE_OTHER) { // We've been redirected, follow the new URL final String followUrl = urlConnection.getHeaderField("Location"); Log.e(TAG, "Redirected to: " + followUrl); return getBytes(followUrl, "", cached); } else { Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")"); return new byte[] {}; } } finally { urlConnection.disconnect(); } }
From source file:Main.java
public static boolean deleteRequest(String query) { HttpURLConnection connection = null; try {// w ww . j a v a2 s . co m connection = (HttpURLConnection) new URL(url + query).openConnection(); connection.setRequestMethod("DELETE"); connection.setRequestProperty("Accept-Charset", charset); statusCode = connection.getResponseCode(); if (statusCode != 200) { return false; } } catch (IOException e) { e.printStackTrace(); } return true; }