List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:vocab.VocabUtils.java
/** * Jena fails to load models in https with content negotiation. Therefore I do * the negotiation here directly/*from w w w.ja v a 2s .com*/ */ private static void doContentNegotiation(OntModel model, Vocabulary v, String accept, String serialization) { try { model.read(v.getUri(), null, serialization); } catch (Exception e) { try { System.out.println("Failed to read the ontology. Doing content negotiation"); URL url = new URL(v.getUri()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", accept); int status = connection.getResponseCode(); if (status == HttpURLConnection.HTTP_SEE_OTHER || status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) { String newUrl = connection.getHeaderField("Location"); //v.setUri(newUrl); connection = (HttpURLConnection) new URL(newUrl).openConnection(); connection.setRequestProperty("Accept", accept); InputStream in = (InputStream) connection.getInputStream(); model.read(in, null, serialization); } } catch (Exception e2) { System.out.println("Failed to read the ontology"); } } }
From source file:com.book.jtm.chap03.HttpClientDemo.java
public static void sendRequest(String method, String url) throws IOException { InputStream is = null;/*from w w w . j a v a2 s. com*/ try { URL newUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) newUrl.openConnection(); // ?10 conn.setReadTimeout(10000); // 15 conn.setConnectTimeout(15000); // ?,GET"GET",post"POST" conn.setRequestMethod("GET"); // ?? conn.setDoInput(true); // ??,???? conn.setDoOutput(true); // Header conn.setRequestProperty("Connection", "Keep-Alive"); // ? List<NameValuePair> paramsList = new ArrayList<NameValuePair>(); paramsList.add(new BasicNameValuePair("username", "mr.simple")); paramsList.add(new BasicNameValuePair("pwd", "mypwd")); writeParams(conn.getOutputStream(), paramsList); // ? conn.connect(); is = conn.getInputStream(); // ? String result = convertStreamToString(is); Log.i("", "### : " + result); } finally { if (is != null) { is.close(); } } }
From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java
/** * Likes video with given position.//from ww w. ja va 2s. c om */ public static boolean like(final String innerurl) { try { String url = "https://graph.facebook.com/me/og.likes"; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 " + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7"); conn.setRequestMethod("POST"); conn.setDoOutput(true); StringBuilder sb = new StringBuilder(); sb.append("method="); sb.append("POST"); sb.append("&"); sb.append("access_token="); sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK).getAccessToken()); sb.append("&"); sb.append("object="); sb.append(URLEncoder.encode(innerurl)); String params = sb.toString(); conn.getOutputStream().write(params.getBytes("UTF-8")); String response = ""; try { InputStream in = conn.getInputStream(); StringBuilder sbr = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sbr.append(line); } in.close(); response = sbr.toString(); } catch (FileNotFoundException e) { InputStream in = conn.getErrorStream(); StringBuilder sbr = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sbr.append(line); } in.close(); response = sbr.toString(); Log.e(TAG, "response = " + response); } try { JSONObject obj = new JSONObject(response); obj.getString("id"); return true; } catch (JSONException jSONEx) { // fb // // ? ? ? ? ? conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; U; " + "CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 " + "(KHTML, like Gecko) Version/4.0.5 Mobile/8A293 " + "Safari/6531.22.7"); conn.setRequestMethod("POST"); conn.setDoOutput(true); sb = new StringBuilder(); sb.append("method="); sb.append("POST"); sb.append("&"); sb.append("access_token="); sb.append(Authorization.getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK) .getAccessToken()); sb.append("&"); sb.append("object="); sb.append(URLEncoder.encode(innerurl)); params = sb.toString(); conn.getOutputStream().write(params.getBytes("UTF-8")); try { InputStream in = conn.getInputStream(); StringBuilder sbr = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000); for (String line = r.readLine(); line != null; line = r.readLine()) { sbr.append(line); } in.close(); response = sbr.toString(); Log.e(TAG, "response2 = " + response); try { JSONObject obj = new JSONObject(response); obj.getString("id"); return true; } catch (JSONException e) { return false; } } catch (FileNotFoundException e) { return false; } } } catch (MalformedURLException mURLEx) { Log.d("", ""); return false; } catch (IOException iOEx) { Log.d("", ""); return false; } catch (Exception ex) { Log.d("", ""); return false; } }
From source file:com.wx.kernel.util.HttpKit.java
private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException { URL _url = new URL(url); HttpURLConnection conn = (HttpURLConnection) _url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory); ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier); }//from w ww.ja v a 2s . c o m conn.setRequestMethod(method); conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(19000); conn.setReadTimeout(19000); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36"); if (headers != null && !headers.isEmpty()) for (Entry<String, String> entry : headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); return conn; }
From source file:com.webarch.common.net.http.HttpService.java
/** * ?url//from w w w . j a v a 2 s .c om * * @param inputStream ? * @param fileName ?? * @param fileType * @param contentType * @param identity * @return */ public static String uploadMediaFile(String requestUrl, FileInputStream inputStream, String fileName, String fileType, String contentType, String identity) { String lineEnd = System.getProperty("line.separator"); String twoHyphens = "--"; String boundary = "*****"; String result = null; try { //? URL submit = new URL(requestUrl); HttpURLConnection conn = (HttpURLConnection) submit.openConnection(); // conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); //? conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", DEFAULT_CHARSET); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //?? DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + ";Content-Type=\"" + contentType + lineEnd); dos.writeBytes(lineEnd); byte[] buffer = new byte[8192]; // 8k int count = 0; while ((count = inputStream.read(buffer)) != -1) { dos.write(buffer, 0, count); } inputStream.close(); //? dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); dos.flush(); InputStream is = conn.getInputStream(); InputStreamReader isr = new InputStreamReader(is, DEFAULT_CHARSET); BufferedReader br = new BufferedReader(isr); result = br.readLine(); dos.close(); is.close(); } catch (IOException e) { logger.error("", e); } return result; }
From source file:com.data.pack.Util.java
/** * Connect to an HTTP URL and return the response as a string. * //from w ww . j a v a 2 s . c o m * Note that the HTTP method override is used on non-GET requests. (i.e. * requests are made as "POST" with method specified in the body). * * @param url * - the resource to open: must be a welformed URL * @param method * - the HTTP method to use ("GET", "POST", etc.) * @param params * - the query parameter for the URL (e.g. access_token=foo) * @return the URL contents as a String * @throws MalformedURLException * - if the URL format is invalid * @throws IOException * - if a network problem occurs */ public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; OutputStream os; if (method.equals("GET")) { url = url + "?" + encodeUrl(params); } Util.logd("Facebook-Util", method + " URL: " + url); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK"); if (!method.equals("GET")) { Bundle dataparams = new Bundle(); for (String key : params.keySet()) { if (params.getByteArray(key) != null) { dataparams.putByteArray(key, params.getByteArray(key)); } } // use method override if (!params.containsKey("method")) { params.putString("method", method); } if (params.containsKey("access_token")) { String decoded_token = URLDecoder.decode(params.getString("access_token")); params.putString("access_token", decoded_token); } conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); os = new BufferedOutputStream(conn.getOutputStream()); os.write(("--" + strBoundary + endLine).getBytes()); os.write((encodePostBody(params, strBoundary)).getBytes()); os.write((endLine + "--" + strBoundary + endLine).getBytes()); if (!dataparams.isEmpty()) { for (String key : dataparams.keySet()) { os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes()); os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes()); os.write(dataparams.getByteArray(key)); os.write((endLine + "--" + strBoundary + endLine).getBytes()); } } os.flush(); } String response = ""; try { response = read(conn.getInputStream()); } catch (FileNotFoundException e) { // Error Stream contains JSON that we can parse to a FB error response = read(conn.getErrorStream()); } return response; }
From source file:io.andyc.papercut.api.PrintApi.java
/** * Queries the remote Papercut server to get the status of the file * * e.g./* w w w . j av a 2 s .co m*/ * * {"status":{"code":"hold-release","complete":false,"text":"Held in a * queue","formatted":"Held in a queue"},"documentName":"test.rtf", * "printer":"Floor1 (Full Colour)","pages":1,"cost":"$0.10"} * * @param printJob {PrintJob} - the file to check the status on * * @return {String} - JSON String which includes file metadata * * @throws NoStatusURLSetException * @throws IOException */ public static PrintStatusData getFileStatus(PrintJob printJob) throws NoStatusURLSetException, IOException { if (Objects.equals(printJob.getStatusCheckURL(), "") || printJob.getStatusCheckURL() == null) { throw new NoStatusURLSetException(); } // from: http://stackoverflow.com/a/29889139/2605221 StringBuilder stringBuffer = new StringBuilder(""); URL url = new URL(printJob.getStatusCheckURL()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", ""); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); connection.setDoInput(true); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = rd.readLine()) != null) { stringBuffer.append(line); } return new ObjectMapper().readValue(stringBuffer.toString(), PrintStatusData.class); }
From source file:net.ftb.util.DownloadUtils.java
/** * Checks the file for corruption.// ww w . j av a2 s . co m * @param file - File to check * @param url - base url to grab md5 with old method * @return boolean representing if it is valid * @throws IOException */ public static boolean backupIsValid(File file, String url) throws IOException { Logger.logInfo("Issue with new md5 method, attempting to use backup method."); String content = null; Scanner scanner = null; String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer())) ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer()) : Locations.masterRepo; resolved += "/md5/FTB2/" + url; HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); int response = connection.getResponseCode(); if (response == 200) { scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); } if (response != 200 || (content == null || content.isEmpty())) { for (String server : backupServers.values()) { resolved = "http://" + server + "/md5/FTB2/" + url.replace("/", "%5E"); connection = (HttpURLConnection) new URL(resolved).openConnection(); connection.setRequestProperty("Cache-Control", "no-transform"); response = connection.getResponseCode(); if (response == 200) { scanner = new Scanner(connection.getInputStream()); scanner.useDelimiter("\\Z"); content = scanner.next(); if (content != null && !content.isEmpty()) { break; } } } } } catch (IOException e) { } finally { connection.disconnect(); if (scanner != null) { scanner.close(); } } String result = fileMD5(file); Logger.logInfo("Local: " + result.toUpperCase()); Logger.logInfo("Remote: " + content.toUpperCase()); return content.equalsIgnoreCase(result); }
From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java
/** * Sends a POST request with an attached object * @param url the url that should be opened * @param params the body parameters/*from w w w . java2s . com*/ * @param attachment the object to be attached * @return the response * @throws IOException */ public static String postWithAttachment(String url, Map<String, String> params, Object attachment) throws IOException { String boundary = generateBoundaryString(10); URL servUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) servUrl.openConnection(); conn.setRequestProperty("User-Agent", System.getProperties().getProperty("http.agent") + SOCIALLIB); conn.setRequestMethod("POST"); String contentType = "multipart/form-data; boundary=" + boundary; conn.setRequestProperty("Content-Type", contentType); byte[] body = generatePostBody(params, attachment, boundary); conn.setDoOutput(true); conn.connect(); OutputStream out = conn.getOutputStream(); out.write(body); InputStream is = null; try { is = conn.getInputStream(); } catch (FileNotFoundException e) { is = conn.getErrorStream(); } catch (Exception e) { int statusCode = conn.getResponseCode(); Log.e("Response code", "" + statusCode); return conn.getResponseMessage(); } BufferedReader r = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String l; while ((l = r.readLine()) != null) sb.append(l).append('\n'); out.close(); is.close(); if (conn != null) conn.disconnect(); return sb.toString(); }
From source file:net.drgnome.virtualpack.util.Util.java
public static boolean hasUpdate(int projectID, String version) { try {/* w w w . j a va 2 s. c om*/ HttpURLConnection con = (HttpURLConnection) (new URL( "https://api.curseforge.com/servermods/files?projectIds=" + projectID)).openConnection(); con.setConnectTimeout(5000); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)"); con.setRequestProperty("Pragma", "no-cache"); con.connect(); JSONArray json = (JSONArray) JSONValue.parse(new InputStreamReader(con.getInputStream())); String[] cdigits = ((String) ((JSONObject) json.get(json.size() - 1)).get("name")).toLowerCase() .split("\\."); String[] vdigits = version.toLowerCase().split("\\."); int max = vdigits.length > cdigits.length ? cdigits.length : vdigits.length; int a; int b; for (int i = 0; i < max; i++) { a = b = 0; try { a = Integer.parseInt(cdigits[i]); } catch (Exception e1) { char[] c = cdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { a += (c[j] << ((c.length - (j + 1)) * 8)); } } try { b = Integer.parseInt(vdigits[i]); } catch (Exception e1) { char[] c = vdigits[i].toCharArray(); for (int j = 0; j < c.length; j++) { b += (c[j] << ((c.length - (j + 1)) * 8)); } } if (a > b) { return true; } else if (a < b) { return false; } else if ((i == max - 1) && (cdigits.length > vdigits.length)) { return true; } } } catch (Exception e) { } return false; }