List of usage examples for java.net HttpURLConnection getOutputStream
public OutputStream getOutputStream() throws IOException
From source file:javaphpmysql.JavaPHPMySQL.java
public static void sendPost() { //Creamos un objeto JSON JSONObject jsonObj = new JSONObject(); //Aadimos el nombre, apellidos y email del usuario jsonObj.put("nombre", nombre); jsonObj.put("apellidos", apellidos); jsonObj.put("email", email); //Creamos una lista para almacenar el JSON List l = new LinkedList(); l.addAll(Arrays.asList(jsonObj)); //Generamos el String JSON String jsonString = JSONValue.toJSONString(l); System.out.println("JSON GENERADO:"); System.out.println(jsonString); System.out.println(""); try {/*from w ww . j av a 2 s.co m*/ //Codificar el json a URL jsonString = URLEncoder.encode(jsonString, "UTF-8"); //Generar la URL String url = SERVER_PATH + "listenPost.php"; //Creamos un nuevo objeto URL con la url donde queremos enviar el JSON URL obj = new URL(url); //Creamos un objeto de conexin HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //Aadimos la cabecera con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); //Creamos los parametros para enviar String urlParameters = "json=" + jsonString; // Enviamos los datos por POST con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Capturamos la respuesta del servidor int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } //Mostramos la respuesta del servidor por consola System.out.println(response); //cerramos la conexin in.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.example.makerecg.NetworkUtilities.java
/** * Perform 2-way sync with the server-side ADSampleFrames. We send a request that * includes all the locally-dirty contacts so that the server can process * those changes, and we receive (and return) a list of contacts that were * updated on the server-side that need to be updated locally. * * @param account The account being synced * @param authtoken The authtoken stored in the AccountManager for this * account/* ww w .j av a 2 s . c om*/ * @param serverSyncState A token returned from the server on the last sync * @param dirtyFrames A list of the frames to send to the server * @return A list of frames that we need to update locally */ public static List<ADSampleFrame> syncSampleFrames(Account account, String authtoken, long serverSyncState, List<ADSampleFrame> dirtyFrames) throws JSONException, ParseException, IOException, AuthenticationException { List<JSONObject> jsonFrames = new ArrayList<JSONObject>(); for (ADSampleFrame frame : dirtyFrames) { jsonFrames.add(frame.toJSONObject()); } JSONArray buffer = new JSONArray(jsonFrames); JSONObject top = new JSONObject(); top.put("data", buffer); // Create an array that will hold the server-side ADSampleFrame // that have been changed (returned by the server). final ArrayList<ADSampleFrame> serverDirtyList = new ArrayList<ADSampleFrame>(); // Send the updated frames data to the server //Log.i(TAG, "Syncing to: " + SYNC_URI); URL urlToRequest = new URL(SYNC_URI); HttpURLConnection conn = (HttpURLConnection) urlToRequest.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + authtoken); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(top.toString(1)); writer.flush(); writer.close(); os.close(); //Log.i(TAG, "body="+top.toString(1)); int responseCode = conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { // Our request to the server was successful - so we assume // that they accepted all the changes we sent up, and // that the response includes the contacts that we need // to update on our side... // TODO: Only uploading data for now ... String response = ""; String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } br.close(); //Log.i(TAG, "response="+response); /* final JSONArray serverContacts = new JSONArray(response); Log.d(TAG, response); for (int i = 0; i < serverContacts.length(); i++) { ADSampleFrame rawContact = ADSampleFrame.valueOf(serverContacts.getJSONObject(i)); if (rawContact != null) { serverDirtyList.add(rawContact); } } */ } else { if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) { Log.e(TAG, "Authentication exception in while uploading data"); throw new AuthenticationException(); } else { Log.e(TAG, "Server error in sending sample frames: " + responseCode); throw new IOException(); } } return null; }
From source file:com.fluidops.iwb.luxid.LuxidExtractor.java
public static String authenticate() throws Exception { String token = ""; /* ***** Authentication ****** */ String auth = "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"> <SOAP-ENV:Body> <ns1:authenticate xmlns:ns1=\"http://luxid.temis.com/ws/types\"> " + "<ns1:userName>" + Config.getConfig().getLuxidUserName() + "</ns1:userName> <ns1:userPassword>" + Config.getConfig().getLuxidPassword() + "</ns1:userPassword> </ns1:authenticate> </SOAP-ENV:Body> </SOAP-ENV:Envelope>"; URL authURL = new URL(Config.getConfig().getLuxidServerURL()); HttpURLConnection authconn = (HttpURLConnection) authURL.openConnection(); authconn.setRequestMethod("POST"); authconn.setDoOutput(true);/*from w w w. ja va 2 s . c o m*/ authconn.getOutputStream().write(auth.getBytes()); if (authconn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream stream = authconn.getInputStream(); InputStreamReader read = new InputStreamReader(stream); BufferedReader rd = new BufferedReader(read); String line = ""; if ((line = rd.readLine()) != null) { token = line.substring(line.indexOf("<token>") + "<token>".length(), line.indexOf("</token>")); } rd.close(); } return token; }
From source file:com.zf.util.Post_NetNew.java
/** * ?//from ww w.j a v a 2 s . c om * * @param pams * @param ip * @param port * @return * @throws Exception */ public static String pn(Map<String, String> pams, String ip, int port) throws Exception { if (null == pams) { return ""; } InetSocketAddress addr = new InetSocketAddress(ip, port); Proxy proxy = new Proxy(Type.HTTP, addr); String strtmp = "url"; URL url = new URL(pams.get(strtmp)); pams.remove(strtmp); strtmp = "body"; String body = pams.get(strtmp); pams.remove(strtmp); strtmp = "POST"; if (StringUtils.isEmpty(body)) strtmp = "GET"; HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(proxy); httpConn.setConnectTimeout(30000); httpConn.setReadTimeout(30000); httpConn.setUseCaches(false); httpConn.setRequestMethod(strtmp); for (String pam : pams.keySet()) { httpConn.setRequestProperty(pam, pams.get(pam)); } if ("POST".equals(strtmp)) { httpConn.setDoOutput(true); httpConn.setDoInput(true); DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream()); dos.writeBytes(body); dos.flush(); } int resultCode = httpConn.getResponseCode(); StringBuilder sb = new StringBuilder(); sb.append(resultCode).append("\n"); String readLine; InputStream stream; try { stream = httpConn.getInputStream(); } catch (Exception ignored) { stream = httpConn.getErrorStream(); } try { BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); while ((readLine = responseReader.readLine()) != null) { sb.append(readLine).append("\n"); } } catch (Exception ignored) { } return sb.toString(); }
From source file:com.amazon.pay.impl.Util.java
/** * This method uses HttpURLConnection instance to make requests. * * @param method The HTTP method (GET,POST,PUT,etc.). * @param url The URL//from w w w . j a v a2s . c om * @param urlParameters URL Parameters * @param headers Header key-value pairs * @return ResponseData * @throws IOException */ public static ResponseData httpSendRequest(String method, String url, String urlParameters, Map<String, String> headers) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); if (headers != null && !headers.isEmpty()) { for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } } con.setDoOutput(true); con.setRequestMethod(method); if (urlParameters != null) { DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); } int responseCode = con.getResponseCode(); BufferedReader in; if (responseCode != 200) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine).append(LINE_SEPARATOR); } in.close(); return new ResponseData(responseCode, response.toString()); }
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 a v a2 s . co 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:net.daporkchop.porkselfbot.util.HTTPUtils.java
/** * Performs a POST request to the specified URL and returns the result. * <p />//w ww .j a va 2 s. c o m * The POST data will be encoded in UTF-8 as the specified contentType. The response will be parsed as UTF-8. * If the server returns an error but still provides a body, the body will be returned as normal. * If the server returns an error without any body, a relevant {@link java.io.IOException} will be thrown. * * @param url URL to submit the POST request to * @param post POST data in the correct format to be submitted * @param contentType Content type of the POST data * @return Raw text response from the server * @throws IOException The request was not successful */ public static String performPostRequest(final URL url, final String post, final String contentType) throws IOException { Validate.notNull(url); Validate.notNull(post); Validate.notNull(contentType); final HttpURLConnection connection = createUrlConnection(url); final byte[] postAsBytes = post.getBytes(Charsets.UTF_8); connection.setRequestProperty("Content-Type", contentType + "; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + postAsBytes.length); connection.setDoOutput(true); OutputStream outputStream = null; try { outputStream = connection.getOutputStream(); IOUtils.write(postAsBytes, outputStream); } finally { IOUtils.closeQuietly(outputStream); } InputStream inputStream = null; try { inputStream = connection.getInputStream(); final String result = IOUtils.toString(inputStream, Charsets.UTF_8); return result; } catch (final IOException e) { IOUtils.closeQuietly(inputStream); inputStream = connection.getErrorStream(); if (inputStream != null) { final String result = IOUtils.toString(inputStream, Charsets.UTF_8); return result; } else { throw e; } } finally { IOUtils.closeQuietly(inputStream); } }
From source file:com.intellij.lang.jsgraphql.languageservice.JSGraphQLNodeLanguageServiceClient.java
private static <R> R executeRequest(Request request, Class<R> responseClass, @NotNull Project project, boolean setProjectDir) { URL url = getJSGraphQLNodeLanguageServiceInstance(project, setProjectDir); if (url == null) { return null; }/*from ww w . j a v a 2s . c o m*/ HttpURLConnection httpConnection = null; try { httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(50); httpConnection.setReadTimeout(1000); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setRequestProperty("Content-Type", "application/json"); httpConnection.connect(); try (OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream())) { final String jsonRequest = new Gson().toJson(request); writer.write(jsonRequest); writer.flush(); writer.close(); } if (httpConnection.getResponseCode() == 200) { if (responseClass == null) { return null; } try (InputStream inputStream = httpConnection.getInputStream()) { String jsonResponse = IOUtils.toString(inputStream, "UTF-8"); R response = new Gson().fromJson(jsonResponse, responseClass); return response; } } else { log.warn("Got error from JS GraphQL Language Service: HTTP " + httpConnection.getResponseCode() + ": " + httpConnection.getResponseMessage()); } } catch (IOException e) { log.warn("Unable to connect to dev server", e); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } return null; }
From source file:flow.visibility.tapping.OpenDaylightHelper.java
/** The function for inserting the flow */ public static boolean installFlow(JSONObject postData, String user, String password, String baseURL) { StringBuffer result = new StringBuffer(); /** Check the connection to ODP REST API page */ try {// w w w . j a v a2 s. c om if (!baseURL.contains("http")) { baseURL = "http://" + baseURL; } baseURL = baseURL + "/controller/nb/v2/flowprogrammer/default/node/OF/" + postData.getJSONObject("node").get("id") + "/staticFlow/" + postData.get("name"); /** Create URL = base URL + container */ URL url = new URL(baseURL); /** Create authentication string and encode it to Base64*/ String authStr = user + ":" + password; String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes()); /** Create Http connection */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /** Set connection properties */ connection.setRequestMethod("PUT"); connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr); connection.setRequestProperty("Content-Type", "application/json"); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); /** Set JSON Post Data */ OutputStream os = connection.getOutputStream(); os.write(postData.toString().getBytes()); os.close(); /** Get the response from connection's inputStream */ InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content)); String line = ""; while ((line = in.readLine()) != null) { result.append(line); } } catch (Exception e) { e.printStackTrace(); } /** checking the result of REST API connection */ if ("success".equalsIgnoreCase(result.toString())) { return true; } else { return false; } }
From source file:com.baasbox.service.push.providers.GCMServer.java
public static void validateApiKey(String apikey) throws MalformedURLException, IOException, PushInvalidApiKeyException { Message message = new Message.Builder().addData("message", "validateAPIKEY").build(); Sender sender = new Sender(apikey); List<String> deviceid = new ArrayList<String>(); deviceid.add("ABC"); Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); jsonRequest.put(JSON_REGISTRATION_IDS, deviceid); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); }/* ww w. ja v a 2 s . com*/ String requestBody = JSONValue.toJSONString(jsonRequest); String url = com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); byte[] bytes = requestBody.getBytes(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "key=" + apikey); OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); int status = conn.getResponseCode(); if (status != 200) { if (status == 401) { throw new PushInvalidApiKeyException("Wrong api key"); } if (status == 503) { throw new UnknownHostException(); } } }