List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.lostad.app.base.util.RequestUtil.java
/** * HTTP??????,??? /*from w w w .j a v a2 s.c o m*/ * @param actionUrl * @param params ? key???,value? * @param files * @throws Exception */ public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token) throws Exception { try { String BOUNDARY = "---------7d4a6d158c9"; //? String MULTIPART_FORM_DATA = "multipart/form-data"; URL url = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true);//? conn.setDoOutput(true);//? conn.setUseCaches(false);//?Cache conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); conn.setRequestProperty("token", token); //???? StringBuilder sb = new StringBuilder(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) {//? sb.append("--"); sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"); sb.append(entry.getValue()); sb.append("\r\n"); } } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(sb.toString().getBytes());//???? //?? for (FormFile file : files) { StringBuilder split = new StringBuilder(); split.append("--"); split.append(BOUNDARY); split.append("\r\n"); split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\"" + file.getFilname() + "\"\r\n"); split.append("Content-Type: " + file.getContentType() + "\r\n\r\n"); outStream.write(split.toString().getBytes()); outStream.write(file.getData(), 0, file.getData().length); outStream.write("\r\n".getBytes()); } byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//?? outStream.write(end_data); outStream.flush(); int cah = conn.getResponseCode(); if (cah != 200) throw new RuntimeException("url"); InputStream is = conn.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } outStream.close(); conn.disconnect(); return b.toString(); } catch (Exception e) { throw e; } }
From source file:com.crawler.app.run.CrawlSiteController.java
public static Boolean checkWebSite(URL url) { HttpURLConnection connection; int code = 0; try {//from w w w.ja v a 2 s . c o m connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); code = connection.getResponseCode(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (code == 200) { return true; } else { return false; } }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * // ww w .j a v a2 s . com * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:com.memetix.mst.MicrosoftTranslatorAPI.java
/** * Gets the OAuth access token.//from w w w .j a v a 2 s . co m * @param clientId The Client key. * @param clientSecret The Client Secret */ public static String getToken(final String clientId, final String clientSecret) throws Exception { final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com" + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret=" + URLEncoder.encode(clientSecret, ENCODING); final URL url = new URL(DatamarketAccessUri); final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); uc.setRequestMethod("POST"); uc.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream()); wr.write(params); wr.flush(); try { final int responseCode = uc.getResponseCode(); final String result = inputStreamToString(uc.getInputStream()); if (responseCode != 200) { throw new Exception("Error from Microsoft Translator API: " + result); } return result; } finally { if (uc != null) { uc.disconnect(); } } }
From source file:com.melniqw.instagramsdk.Network.java
private static String sendDummyRequest(String url, String body, Request request) throws IOException { HttpURLConnection connection = null; try {/*from w ww . j a v a 2s . co m*/ connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(10000); connection.setReadTimeout(10000); connection.setUseCaches(false); connection.setDoInput(true); // connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); if (request == Request.GET) { connection.setDoOutput(false); connection.setRequestMethod("GET"); } else if (request == Request.POST) { connection.setDoOutput(true); connection.setRequestMethod("POST"); } if (REQUEST_ENABLE_COMPRESSION) connection.setRequestProperty("Accept-Encoding", "gzip"); if (request == Request.POST) connection.getOutputStream().write(body.getBytes("utf-8")); int code = connection.getResponseCode(); System.out.println(TAG + " responseCode = " + code); //It may happen due to keep-alive problem http://stackoverflow.com/questions/1440957/httpurlconnection-getresponsecode-returns-1-on-second-invocation if (code == -1) throw new WrongResponseCodeException("Network error"); // ? 200 //on error can also read error stream from connection. InputStream inputStream = new BufferedInputStream(connection.getInputStream(), 8192); String encoding = connection.getHeaderField("Content-Encoding"); if (encoding != null && encoding.equalsIgnoreCase("gzip")) inputStream = new GZIPInputStream(inputStream); String response = Utils.convertStreamToString(inputStream); System.out.println(TAG + " response = " + response); return response; } finally { if (connection != null) connection.disconnect(); } }
From source file:edu.samplu.common.ITUtil.java
public static String getHTML(String urlToRead) { URL url;/*from www. j av a 2 s. c o m*/ HttpURLConnection conn; BufferedReader rd; String line; String result = ""; try { url = new URL(urlToRead); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { result += line; } rd.close(); } catch (Exception e) { e.printStackTrace(); } return result; }
From source file:crow.util.Util.java
public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException { int responseCode = -1; OutputStream osw = null;//from ww w . j a v a 2 s . c o m try { conn.setConnectTimeout(20000); conn.setReadTimeout(12000); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); byte[] bytes = encodePostParam.getBytes("UTF-8"); conn.setRequestProperty("Content-Length", Integer.toString(bytes.length)); osw = conn.getOutputStream(); osw.write(bytes); osw.flush(); responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new IOException(""); } else { String s = inputStreamToString(conn.getInputStream()); return s; } } finally { try { if (osw != null) osw.close(); } catch (Exception ignore) { } } }
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. *//*from w ww .j a v a2s. co m*/ 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:eu.crowdrec.contest.sender.RequestSender.java
/** * Send a line from a logFile to an HTTP server (single-threaded). * //from w w w. j ava 2 s . c om * @param logline the line that should by sent * * @param connection the connection to the http server, must not be null * * @return the response or null (if an error has been detected) */ static private String excutePost(final String logline, final String serverURL) { // split the logLine into several token String[] token = logline.split("\t"); String type = token[0]; String property = token[3]; String entity = token[4]; // encode the content as URL parameters. String urlParameters = ""; try { urlParameters = String.format("type=%s&properties=%s&entities=%s", URLEncoder.encode(type, "UTF-8"), URLEncoder.encode(property, "UTF-8"), URLEncoder.encode(entity, "UTF-8")); } catch (UnsupportedEncodingException e1) { logger.warn(e1.toString()); } // initialize a HTTP connection to the server // reuse of connection objects is delegated to the JVM HttpURLConnection connection = null; try { final URL url = new URL(serverURL); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Language", "en-US"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length)); // Send request DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); // Get Response BufferedReader rd = null; InputStream is = null; try { is = connection.getInputStream(); rd = new BufferedReader(new InputStreamReader(is)); StringBuffer response = new StringBuffer(); for (String line = rd.readLine(); line != null; line = rd.readLine()) { response.append(line); response.append(" "); } return response.toString(); } catch (IOException e) { logger.warn("receivind response failed, ignored."); } finally { if (is != null) { is.close(); } if (rd != null) { rd.close(); } } } catch (MalformedURLException e) { System.err.println("invalid server URL, program stopped."); System.exit(-1); } catch (IOException e) { System.err.println("i/o error connecting the http server, program stopped. e=" + e); System.exit(-1); } catch (Exception e) { System.err.println("general error connecting the http server, program stopped. e:" + e); e.printStackTrace(); System.exit(-1); } finally { // close the connection if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends an HTTP GET request to a url/* www.j a v a2 s .co m*/ * * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search") * @param file the output file. If it is a folder, it tries to get the file name from the header. * @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). * Note: This method will add the question mark (?) to the request - * DO NOT add it yourself * @param user user. * @param password password. * @return the file written. * @throws Exception if something goes wrong. */ public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user, String password) throws Exception { if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } HttpURLConnection conn = makeNewConnection(urlStr); conn.setRequestMethod("GET"); // 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(); if (file.isDirectory()) { // try to get the header String headerField = conn.getHeaderField("Content-Disposition"); String fileName = null; if (headerField != null) { String[] split = headerField.split(";"); for (String string : split) { String pattern = "filename="; if (string.toLowerCase().startsWith(pattern)) { fileName = string.replaceFirst(pattern, ""); break; } } } if (fileName == null) { // give a name fileName = "FILE_" + TimeUtilities.INSTANCE.TIMESTAMPFORMATTER_LOCAL.format(new Date()); } file = new File(file, fileName); } InputStream in = null; FileOutputStream out = null; try { in = conn.getInputStream(); out = new FileOutputStream(file); byte[] buffer = new byte[(int) maxBufferSize]; int bytesRead = in.read(buffer, 0, (int) maxBufferSize); while (bytesRead > 0) { out.write(buffer, 0, bytesRead); bytesRead = in.read(buffer, 0, (int) maxBufferSize); } out.flush(); } finally { if (in != null) in.close(); if (out != null) out.close(); if (conn != null) conn.disconnect(); } return file; }