List of usage examples for java.net HttpURLConnection setRequestMethod
public void setRequestMethod(String method) throws ProtocolException
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Connects to the server, authenticates the provided username and * password.// www . j ava 2 s.c o m * * @param username The user's username * @param password The user's password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String accessKey, String base_url) { String token = null; String hash = null; authenticate_log_text = "authenticate()\n"; AUTH_URI = base_url + "/webservice.php"; authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username=" + username + "\n"; Log.d(TAG, "AUTH_URI : "); Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); // =========== get challenge token ============================== ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); try { URL url; // HTTP GET REQUEST url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setUseCaches(false); // for some site that redirects based on user agent con.setInstanceFollowRedirects(true); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15"); con.setAllowUserInteraction(false); int timeout = 20000; con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n"; switch (status) { case 200: case 201: case 302: 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(); Log.d(TAG, "message body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "body : " + sb.toString(); if (status == 302) { authenticate_log_text = sb.toString(); return null; } JSONObject result = new JSONObject(sb.toString()); Log.d(TAG, result.getString("result")); JSONObject data = new JSONObject(result.getString("result")); token = data.getString("token"); break; case 401: Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "Server auth error"; return null; default: Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "connection status code :" + status; return null; } } catch (ClientProtocolException e) { Log.i(TAG, "getchallenge:http protocol error"); Log.e(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n"; return null; } catch (IOException e) { Log.e(TAG, "getchallenge: IO Exception"); Log.e(TAG, e.getMessage()); Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n"; return null; } catch (JSONException e) { Log.i(TAG, "json exception"); authenticate_log_text = authenticate_log_text + "JSon exception\n"; // TODO Auto-generated catch block e.printStackTrace(); return null; } // ================= login ================== try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(token.getBytes()); m.update(accessKey.getBytes()); hash = new BigInteger(1, m.digest()).toString(16); Log.i(TAG, "hash"); Log.i(TAG, hash); } catch (NoSuchAlgorithmException e) { authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n"; e.printStackTrace(); } try { String charset; charset = "utf-8"; String query = String.format("operation=login&username=%s&accessKey=%s", URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset)); authenticate_log_text = authenticate_log_text + "login()\n"; URLConnection connection = new URL(AUTH_URI).openConnection(); connection.setDoOutput(true); // Triggers POST. int timeout = 20000; connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); connection.setUseCaches(false); OutputStream output = connection.getOutputStream(); try { output.write(query.getBytes(charset)); } finally { try { output.close(); } catch (IOException logOrIgnore) { } } Log.d(TAG, "Query written"); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message post body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n"; JSONObject result = new JSONObject(sb.toString()); String success = result.getString("success"); Log.i(TAG, success); if (success == "true") { Log.i(TAG, result.getString("result")); Log.i(TAG, "sucesssfully logged in is"); JSONObject data = new JSONObject(result.getString("result")); sessionName = data.getString("sessionName"); Log.i(TAG, sessionName); authenticate_log_text = authenticate_log_text + "successfully logged in\n"; return token; } else { // success is false, retrieve error JSONObject data = new JSONObject(result.getString("error")); authenticate_log_text = "can not login :\n" + data.toString(); return null; } //token = data.getString("token"); //Log.i(TAG,token); } catch (ClientProtocolException e) { Log.d(TAG, "login: http protocol error"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (IOException e) { Log.d(TAG, "login: IO Exception"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "login: IO Exception \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (JSONException e) { Log.d(TAG, "JSON exception"); // TODO Auto-generated catch block authenticate_log_text = authenticate_log_text + "JSON exception "; authenticate_log_text = authenticate_log_text + e.getMessage(); e.printStackTrace(); } return null; // ======================================================================== }
From source file:fr.gael.dhus.service.ProductService.java
private static void wcsDeleteCoverage(String coverageId) throws IOException { String GET_URL = "http://localhost:8080/rasdaman/ows?SERVICE=WCS&VERSION=2.0.1&request=DeleteCoverage&coverageId=" + coverageId;/*from w w w . j a v a 2 s . com*/ String USER_AGENT = "Mozilla/5.0"; URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) logger.info("Successfully deleted coverage with id " + coverageId); else logger.error("NoSuchCoverage"); }
From source file:fr.gael.dhus.service.ProductService.java
private static void wmsDeleteLayer(String coverageId) throws IOException { String GET_URL = "http://localhost:8080/rasdaman/ows?service=WMS&version=1.3.0&request=DeleteLayer&layer=" + coverageId;// w w w. j a v a 2 s. c om String USER_AGENT = "Mozilla/5.0"; URL obj = new URL(GET_URL); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) logger.info("Successfully deleted layer with id " + coverageId); else logger.error("NoSuchLayer"); }
From source file:com.example.igorklimov.popularmoviesdemo.helpers.Utility.java
public static String getJsonResponse(String s) { HttpURLConnection connection = null; InputStream input = null;//from w w w.j a va 2 s . c o m BufferedReader reader = null; String JsonResponse = null; try { URL url = new URL(s); Log.d("TAG", url.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); input = connection.getInputStream(); StringBuilder builder = new StringBuilder(); if (input != null) { reader = new BufferedReader(new InputStreamReader(input)); String line; while ((line = reader.readLine()) != null) { builder.append(line).append("\n"); } JsonResponse = builder.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } return JsonResponse; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
public static String login(String email, String pass) throws IOException { // Server URL setup String _url = getBaseUri().appendPath("Login").build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.POST); addRequestHeader(conn, true);//from w w w . j ava 2 s.c o m // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); try { // hash the password pass = Utilities.computeHash(pass); } catch (NoSuchAlgorithmException e) { Log.e(TAG, e.getLocalizedMessage()); } // Build JSON Object jgen.writeStartObject(); jgen.writeStringField(Keys.User.EMAIL, email); jgen.writeStringField("password", pass); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); ps.close(); // Send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); /* * result should get valid={"userID":"##"} * invalid={"errorID":"3","errorMessage":"invalid username or password"} */ String result = ""; if (!response.isEmpty()) { JsonNode tree = MAPPER.readTree(response); if (!tree.has(Keys.User.ID)) { logError(TAG, tree); result = "invalid username or password"; } else result = tree.get(Keys.User.ID).asText(); } conn.disconnect(); return result; }
From source file:com.meetingninja.csse.database.UserDatabaseAdapter.java
/** * Registers a passed in User and returns that user with an assigned UserID * * @param registerMe/*from w ww . j a v a2 s .c o m*/ * @param password * @return the passed-in user with an assigned ID by the server * @throws Exception */ public static User register(User registerMe, String password) throws Exception { // Server URL setup String _url = getBaseUri().build().toString(); // Establish connection URL url = new URL(_url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // add request header conn.setRequestMethod(IRequest.POST); addRequestHeader(conn, true); // prepare POST payload ByteArrayOutputStream json = new ByteArrayOutputStream(); // this type of print stream allows us to get a string easily PrintStream ps = new PrintStream(json); // Create a generator to build the JSON string JsonGenerator jgen = JFACTORY.createGenerator(ps, JsonEncoding.UTF8); password = Utilities.computeHash(password); // Build JSON Object jgen.writeStartObject(); jgen.writeStringField(Keys.User.NAME, registerMe.getDisplayName()); jgen.writeStringField("password", password); jgen.writeStringField(Keys.User.EMAIL, registerMe.getEmail()); jgen.writeStringField(Keys.User.PHONE, registerMe.getPhone()); jgen.writeStringField(Keys.User.COMPANY, registerMe.getCompany()); jgen.writeStringField(Keys.User.TITLE, registerMe.getTitle()); jgen.writeStringField(Keys.User.LOCATION, registerMe.getLocation()); jgen.writeEndObject(); jgen.close(); // Get JSON Object payload from print stream String payload = json.toString("UTF8"); ps.close(); // Send payload int responseCode = sendPostPayload(conn, payload); String response = getServerResponse(conn); User createUser = new User(registerMe); /* * result should get valid={"userID":"##"} */ String result = ""; if (!response.isEmpty()) { JsonNode tree = MAPPER.readTree(response); if (!tree.has(Keys.User.ID)) { result = "duplicate email or username"; } else { result = tree.get(Keys.User.ID).asText(); createUser.setID(result); } } conn.disconnect(); return createUser; }
From source file:com.memetix.mst.MicrosoftTranslatorAPI.java
/** * Forms an HTTP request, sends it using GET method and returns the result of the request as a String. * //from w ww. j a va2 s. c o m * @param url The URL to query for a String response. * @return The translated String. * @throws Exception on error. */ private static String retrieveResponse(final URL url) throws Exception { if (clientId != null && clientSecret != null && System.currentTimeMillis() > tokenExpiration) { String tokenJson = getToken(clientId, clientSecret); Integer expiresIn = Integer .parseInt((String) ((JSONObject) JSONValue.parse(tokenJson)).get("expires_in")); tokenExpiration = System.currentTimeMillis() + ((expiresIn * 1000) - 1); token = "Bearer " + (String) ((JSONObject) JSONValue.parse(tokenJson)).get("access_token"); } final HttpURLConnection uc = (HttpURLConnection) url.openConnection(); if (referrer != null) uc.setRequestProperty("referer", referrer); uc.setRequestProperty("Content-Type", contentType + "; charset=" + ENCODING); uc.setRequestProperty("Accept-Charset", ENCODING); if (token != null) { uc.setRequestProperty("Authorization", token); } uc.setRequestMethod("GET"); uc.setDoOutput(true); 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:net.nym.library.http.UploadImagesRequest.java
/** * ???/*from w w w . ja v a 2 s . c om*/ * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws java.io.IOException */ public static String postFile(String url, Map<String, Object> params, Map<String, File> files) throws IOException { String result = ""; String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; StringBuilder sb = new StringBuilder("?"); for (Map.Entry<String, Object> entry : params.entrySet()) { // sb.append(PREFIX); // sb.append(BOUNDARY); // sb.append(LINEND); // sb.append("Content-Disposition: form-data; name=\"" // + entry.getKey() + "\"" + LINEND); // sb.append("Content-Type: text/plain; charset=" + CHARSET // + LINEND); // sb.append("Content-Transfer-Encoding: 8bit" + LINEND); // sb.append(LINEND); // sb.append(entry.getValue()); // sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); sb.append(entry.getKey()).append("=").append(NetUtil.URLEncode(entry.getValue().toString())) .append("&"); } sb.deleteCharAt(sb.length() - 1); URL uri = new URL(url + sb.toString()); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setConnectTimeout(50000); conn.setDoInput(true);// ? conn.setDoOutput(true);// ? conn.setUseCaches(false); // ?? conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // ? // StringBuilder sb = new StringBuilder(); // for (Map.Entry<String, Object> entry : params.entrySet()) { //// sb.append(PREFIX); //// sb.append(BOUNDARY); //// sb.append(LINEND); //// sb.append("Content-Disposition: form-data; name=\"" //// + entry.getKey() + "\"" + LINEND); //// sb.append("Content-Type: text/plain; charset=" + CHARSET //// + LINEND); //// sb.append("Content-Transfer-Encoding: 8bit" + LINEND); //// sb.append(LINEND); //// sb.append(entry.getValue()); //// sb.append(LINEND); // String key = entry.getKey(); // sb.append("&"); // sb.append(key).append("=").append(params.get(key)); // Log.i("%s=%s",key,params.get(key).toString()); // } DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); // outStream.write(sb.toString().getBytes()); // ? if (files != null) { for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sbFile = new StringBuilder(); sbFile.append(PREFIX); sbFile.append(BOUNDARY); sbFile.append(LINEND); /** * ?? name???key ?key ?? * filename?????? :abc.png */ sbFile.append("Content-Disposition: form-data; name=\"" + file.getKey() + "\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sbFile.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sbFile.append(LINEND); Log.i(sbFile.toString()); outStream.write(sbFile.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // ? byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); } outStream.flush(); // ?? int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sbResult = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sbResult.append((char) ch); } } result = sbResult.toString(); outStream.close(); conn.disconnect(); return result; }
From source file:com.screenslicer.common.CommonUtil.java
public static void setMethod(HttpURLConnection httpURLConnection, String method) { try {// w w w .j a va2 s . c o m httpURLConnection.setRequestMethod(method); // Check whether we are running on a buggy JRE } catch (final ProtocolException pe) { Class<?> connectionClass = httpURLConnection.getClass(); Field delegateField = null; try { delegateField = connectionClass.getDeclaredField("delegate"); delegateField.setAccessible(true); HttpURLConnection delegateConnection = (HttpURLConnection) delegateField.get(httpURLConnection); setMethod(delegateConnection, method); } catch (NoSuchFieldException e) { // Ignore for now, keep going } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } try { Field methodField; while (connectionClass != null) { try { methodField = connectionClass.getDeclaredField("method"); } catch (NoSuchFieldException e) { connectionClass = connectionClass.getSuperclass(); continue; } methodField.setAccessible(true); methodField.set(httpURLConnection, method); break; } } catch (final Exception e) { throw new RuntimeException(e); } } }
From source file:edu.jhu.cvrg.waveform.utility.WebServiceUtility.java
public static Map<String, String> annotationJSONLookup(String restURL, String... key) { Map<String, String> ret = null; URL url;/*from ww w.ja v a2 s.co m*/ HttpURLConnection conn = null; try { if (System.currentTimeMillis() > waitUntil) { url = new URL(restURL); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); BufferedReader in = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String jsonSrc = in.readLine(); in.close(); JSONObject jsonObject = new JSONObject(jsonSrc); ret = new HashMap<String, String>(); for (int i = 0; i < key.length; i++) { Object atr = jsonObject.get(key[i]); String value = ""; if (atr instanceof JSONArray) { JSONArray array = ((JSONArray) atr); for (int j = 0; j < array.length(); j++) { value += array.getString(j); } } else { value = atr.toString(); } if (value.isEmpty()) { value = "No " + key[i] + " found"; } ret.put(key[i], value); } } else { log.warn("Waiting the bioportal server"); } } catch (MalformedURLException mue) { mue.printStackTrace(); } catch (IOException ioe) { //wait for 1 minute waitUntil = System.currentTimeMillis() + (1000 * 60); log.error(ioe.getMessage()); } catch (JSONException e) { e.printStackTrace(); } return ret; }