List of usage examples for java.net HttpURLConnection addRequestProperty
public void addRequestProperty(String key, String value)
From source file:it.polimi.chansonnier.agent.YoutubeGrabber.java
private String getRedirUrl(String url) { String hdr = ""; try {/*w w w .ja v a2 s.c om*/ HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setInstanceFollowRedirects(false); conn.addRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.8) Gecko/20100215 Ubuntu/9.04 (jaunty) Shiretoko/3.5.8"); hdr = conn.getHeaderField("location"); } catch (Exception e) { e.printStackTrace(); return null; } return hdr; }
From source file:blueprint.sdk.google.gcm.GcmSender.java
private GcmResponse send(String json) throws IOException { HttpURLConnection http = (HttpURLConnection) new URL(GCM_URL).openConnection(); http.setRequestMethod("POST"); http.addRequestProperty("Authorization", "key=" + apiKey); http.addRequestProperty("Content-Type", "application/json"); http.setDoOutput(true);// w w w . j ava 2 s .c o m OutputStream os = http.getOutputStream(); os.write(json.getBytes()); os.close(); http.connect(); return decodeResponse(http); }
From source file:ai.api.RequestTask.java
@Override protected String doInBackground(final String... params) { final String payload = params[0]; if (TextUtils.isEmpty(payload)) { throw new IllegalArgumentException("payload argument should not be empty"); }/* w w w.ja va2 s. co m*/ String response = null; HttpURLConnection connection = null; try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.connect(); final BufferedOutputStream outputStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.write(payload, outputStream, Charsets.UTF_8); outputStream.close(); final InputStream inputStream = new BufferedInputStream(connection.getInputStream()); response = IOUtils.toString(inputStream, Charsets.UTF_8); inputStream.close(); return response; } catch (final IOException e) { Log.e(TAG, "Can't make request to the Speaktoit AI service. Please, check connection settings and API access token.", e); } finally { if (connection != null) { connection.disconnect(); } } return null; }
From source file:com.android.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }/* ww w . j ava 2s.c o m*/ map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:org.runnerup.export.GoogleFitSynchronizer.java
private HttpURLConnection getHttpURLConnection(String suffix, RequestMethod requestMethod) throws IOException { URL url = new URL(REST_URL + suffix); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); connect.addRequestProperty("Authorization", "Bearer " + getAccessToken()); connect.addRequestProperty("Accept-Encoding", "gzip"); connect.addRequestProperty("User-Agent", "RunnerUp (gzip)"); if (requestMethod.equals(RequestMethod.GET)) { connect.setDoInput(true);/*from w w w.j av a 2 s. c o m*/ } else { connect.setDoOutput(true); connect.addRequestProperty("Content-Type", "application/json; charset=UTF-8"); connect.addRequestProperty("Content-Encoding", "gzip"); } if (requestMethod.equals(RequestMethod.PATCH)) { connect.addRequestProperty("X-HTTP-Method-Override", "PATCH"); connect.setRequestMethod(RequestMethod.POST.name()); } else { connect.setRequestMethod(requestMethod.name()); } return connect; }
From source file:com.android.volley.toolbox.AuthenticationChallengesProofHurlStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders());/*from w w w .j a v a 2 s .c om*/ map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); /************************/ /****** WORKAROUND ******/ int responseCode; try { // Will throw IOException if server responds with 401. responseCode = connection.getResponseCode(); } catch (IOException e) { // You can get the response code after an exception if you call .getResponseCode() // a second time on the connection object. This is because the first time you // call .getResponseCode() an internal state is set that enables .getResponseCode() // to return without throwing an exception. responseCode = connection.getResponseCode(); } /************************/ if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
From source file:com.example.chengcheng.network.httpstacks.HttpUrlConnStack.java
private void setRequestHeaders(HttpURLConnection connection, Request<?> request) { Set<String> headersKeys = request.getmHeaders().keySet(); for (String headerName : headersKeys) { connection.addRequestProperty(headerName, request.getmHeaders().get(headerName)); }//from w w w . j a va 2s .co m }
From source file:org.alfresco.mobile.android.api.network.NetworkHttpInvoker.java
private static Response invoke(UrlBuilder url, String method, String contentType, Map<String, List<String>> httpHeaders, Output writer, boolean forceOutput, BigInteger offset, BigInteger length, Map<String, String> params) { try {// w w w . j a v a2 s .c om // Log.d("URL", url.toString()); // connect HttpURLConnection conn = (HttpURLConnection) (new URL(url.toString())).openConnection(); conn.setRequestMethod(method); conn.setDoInput(true); conn.setDoOutput(writer != null || forceOutput); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setRequestProperty("User-Agent", ClientVersion.OPENCMIS_CLIENT); // set content type if (contentType != null) { conn.setRequestProperty("Content-Type", contentType); } // set other headers if (httpHeaders != null) { for (Map.Entry<String, List<String>> header : httpHeaders.entrySet()) { if (header.getValue() != null) { for (String value : header.getValue()) { conn.addRequestProperty(header.getKey(), value); } } } } // range BigInteger tmpOffset = offset; if ((tmpOffset != null) || (length != null)) { StringBuilder sb = new StringBuilder("bytes="); if ((tmpOffset == null) || (tmpOffset.signum() == -1)) { tmpOffset = BigInteger.ZERO; } sb.append(tmpOffset.toString()); sb.append("-"); if ((length != null) && (length.signum() == 1)) { sb.append(tmpOffset.add(length.subtract(BigInteger.ONE)).toString()); } conn.setRequestProperty("Range", sb.toString()); } conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); // add url form parameters if (params != null) { DataOutputStream ostream = null; OutputStream os = null; try { os = conn.getOutputStream(); ostream = new DataOutputStream(os); Set<String> parameters = params.keySet(); StringBuffer buf = new StringBuffer(); int paramCount = 0; for (String it : parameters) { String parameterName = it; String parameterValue = (String) params.get(parameterName); if (parameterValue != null) { parameterValue = URLEncoder.encode(parameterValue, "UTF-8"); if (paramCount > 0) { buf.append("&"); } buf.append(parameterName); buf.append("="); buf.append(parameterValue); ++paramCount; } } ostream.writeBytes(buf.toString()); } finally { if (ostream != null) { ostream.flush(); ostream.close(); } IOUtils.closeStream(os); } } // send data if (writer != null) { // conn.setChunkedStreamingMode((64 * 1024) - 1); OutputStream connOut = null; connOut = conn.getOutputStream(); OutputStream out = new BufferedOutputStream(connOut, BUFFER_SIZE); writer.write(out); out.flush(); } // connect conn.connect(); // get stream, if present int respCode = conn.getResponseCode(); InputStream inputStream = null; if ((respCode == HttpStatus.SC_OK) || (respCode == HttpStatus.SC_CREATED) || (respCode == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION) || (respCode == HttpStatus.SC_PARTIAL_CONTENT)) { inputStream = conn.getInputStream(); } // get the response return new Response(respCode, conn.getResponseMessage(), conn.getHeaderFields(), inputStream, conn.getErrorStream()); } catch (Exception e) { throw new CmisConnectionException("Cannot access " + url + ": " + e.getMessage(), e); } }
From source file:py.una.pol.karaku.services.client.WSSecurityInterceptor.java
/** * Agrega seguridad a una llamada a un servicio, para ello agrega dos header * params, pertenecientes a Usuario y Password. * /*from w w w . ja v a 2s . co m*/ * @param user * usuario de la llamada * @param password * contrasea del que invoca el servicio. * @param message * mensaje que actualmente se esta enviando */ public void addSecurity(String user, String password, WebServiceMessage message) { Charset cs = Charset.forName(CharEncoding.UTF_8); TransportContext context = TransportContextHolder.getTransportContext(); HttpUrlConnection connection = (HttpUrlConnection) context.getConnection(); HttpURLConnection uRLConnection = connection.getConnection(); String auth = CREDENTIALS_FORMAT.replace("USER", user).replace("PASSWORD", password); byte[] encode = Base64.encode(auth.getBytes(cs)); uRLConnection.addRequestProperty(AUTHORIZATION_HEADER_PARAM, HEADER_CREDENTIALS_FORMAT.replace("CREDENTIALS", new String(encode, cs))); }
From source file:org.simple.net.httpstacks.HttpUrlConnStack.java
private void setRequestHeaders(HttpURLConnection connection, Request<?> request) { Set<String> headersKeys = request.getHeaders().keySet(); for (String headerName : headersKeys) { connection.addRequestProperty(headerName, request.getHeaders().get(headerName)); }/*from w w w. java 2 s. c o m*/ }