List of usage examples for java.net HttpURLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:Main.java
public static String[] getUrlInfos(String urlAsString, int timeout) { try {//w w w. j av a2 s . c o m URL url = new URL(urlAsString); //using proxy may increase latency HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); hConn.setRequestProperty("User-Agent", "Mozilla/5.0 Gecko/20100915 Firefox/3.6.10"); // on android we got problems because of this // so disable that for now // hConn.setRequestProperty("Accept-Encoding", "gzip, deflate"); hConn.setConnectTimeout(timeout); hConn.setReadTimeout(timeout); // default length of bufferedinputstream is 8k byte[] arr = new byte[K4]; InputStream is = hConn.getInputStream(); if ("gzip".equals(hConn.getContentEncoding())) is = new GZIPInputStream(is); BufferedInputStream in = new BufferedInputStream(is, arr.length); in.read(arr); return getUrlInfosFromText(arr, hConn.getContentType()); } catch (Exception ex) { } return new String[] { "", "" }; }
From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}.//from www .j a v a2 s . c o m * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. * @author Sections of this code contributed by jTribe (http://jtribe.com.au) */ protected static synchronized String getUrlContent(String sUrl, String email, String pword) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } String userPassword = email + ":" + pword; String encoding = Base64Coder.encodeString(userPassword); try { URL url = new URL(sUrl); System.setProperty("http.keepAlive", "false"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setRequestProperty("User-Agent", sUserAgent); connection.setRequestMethod("GET"); //Get response code int responseCode = connection.getResponseCode(); if (responseCode != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + connection.getResponseMessage()); } // Pull content stream from response InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
From source file:org.droidparts.http.worker.HttpURLConnectionWorker.java
public static void postOrPut(HttpURLConnection conn, String contentType, String data) throws HTTPException { conn.setRequestProperty("Accept-Charset", UTF8); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Connection", "Keep-Alive"); OutputStream os = null;//from ww w .ja va 2 s . c o m try { os = conn.getOutputStream(); os.write(data.getBytes(UTF8)); } catch (Exception e) { throw new HTTPException(e); } finally { silentlyClose(os); } }
From source file:Main.java
public static void post(String actionUrl, String file) { try {// ww w .j av a 2s . co m URL url = new URL(actionUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestMethod("POST"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary=*****"); DataOutputStream ds = new DataOutputStream(con.getOutputStream()); FileInputStream fStream = new FileInputStream(file); int bufferSize = 1024; // 1MB byte[] buffer = new byte[bufferSize]; int bufferLength = 0; int length; while ((length = fStream.read(buffer)) != -1) { bufferLength = bufferLength + 1; ds.write(buffer, 0, length); } fStream.close(); ds.flush(); InputStream is = con.getInputStream(); int ch; StringBuilder b = new StringBuilder(); while ((ch = is.read()) != -1) { b.append((char) ch); } new String(b.toString().getBytes("ISO-8859-1"), "utf-8"); ds.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (ProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.appdynamics.common.RESTClient.java
public static void sendPost(String urlString, String input, String apiKey) { try {//from w w w . j ava 2 s .c o m URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64((apiKey).getBytes()))); OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; logger.info("Output from Server .... \n"); while ((output = br.readLine()) != null) { logger.info(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:ee.ria.xroad.signer.certmanager.OcspClient.java
private static HttpURLConnection createConnection(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty(MimeUtils.HEADER_CONTENT_TYPE, MimeTypes.OCSP_REQUEST); connection.setRequestProperty("Accept", MimeTypes.OCSP_RESPONSE); connection.setDoOutput(true);/*from w ww . ja v a 2s .c o m*/ connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setReadTimeout(READ_TIMEOUT_MS); connection.connect(); return connection; }
From source file:Main.java
public static URI unredirect(URI uri) throws IOException { if (!REDIRECTOR_DOMAINS.contains(uri.getHost())) { return uri; }// ww w. j a va 2s. co m URL url = uri.toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoInput(false); connection.setRequestMethod("HEAD"); connection.setRequestProperty("User-Agent", "ZXing (Android)"); try { connection.connect(); switch (connection.getResponseCode()) { case HttpURLConnection.HTTP_MULT_CHOICE: case HttpURLConnection.HTTP_MOVED_PERM: case HttpURLConnection.HTTP_MOVED_TEMP: case HttpURLConnection.HTTP_SEE_OTHER: case 307: // No constant for 307 Temporary Redirect ? String location = connection.getHeaderField("Location"); if (location != null) { try { return new URI(location); } catch (URISyntaxException e) { // nevermind } } } return uri; } finally { connection.disconnect(); } }
From source file:ilearnrw.utils.ServerHelperClass.java
public static String sendGet(String link) throws Exception { String url = baseUrl + link;/*w w w . java2s . c om*/ URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod("GET"); con.setRequestProperty("Authorization", userNamePasswordBase64("api", "api")); //con.setRequestProperty("User-Agent", USER_AGENT); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return response.toString(); }
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 {/*ww w . jav a2 s . c o 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:net.daporkchop.porkbot.util.HTTPUtils.java
/** * Performs a POST request to the specified URL and returns the result. * <p/>//from www . j av a 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(@NonNull URL url, @NonNull String post, @NonNull String contentType) throws IOException { 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); } return sendRequest(connection); }