/** * returns the inputstream from URLConnection * * @return InputStream */ public InputStream getInputStream() { try { int responseCode = this.urlConnection.getResponseCode(); try { // HACK: manually follow redirects, for the login to work // HTTPUrlConnection auto redirect doesn't respect the provided headers if (responseCode == 302) { HttpClient redirectClient = new HttpClient( proxyHost, proxyPort, urlConnection.getHeaderField("Location"), headers, urlConnection.getRequestMethod(), callback); redirectClient.getInputStream().close(); } } catch (Throwable e) { System.out.println("Following redirect failed"); } setCookieHeader = this.urlConnection.getHeaderField("Set-Cookie"); InputStream in = responseCode != HttpURLConnection.HTTP_OK ? this.urlConnection.getErrorStream() : this.urlConnection.getInputStream(); return in; } catch (Exception e) { return null; } }
@Override public String toString() { return uc.getRequestMethod() + " " + uc.getURL() + " returned a response status of " + this.getStatus() + " " + this.getClientResponseStatus(); }
public void a(HttpURLConnection httpurlconnection, Object obj) { a("=== HTTP Request ==="); a( (new StringBuilder()) .append(httpurlconnection.getRequestMethod()) .append(" ") .append(httpurlconnection.getURL().toString()) .toString()); if (obj instanceof String) { a((new StringBuilder()).append("Content: ").append((String) obj).toString()); } a(httpurlconnection.getRequestProperties()); }
/** * 计算签名 * * @param conn 连接 * @param uri 请求地址 * @param length 请求所发Body数据长度 * @return 签名字符串 */ private String sign(HttpURLConnection conn, String uri, long length) { String sign = conn.getRequestMethod() + "&" + uri + "&" + conn.getRequestProperty(DATE) + "&" + length + "&" + password; return "UpYun " + userName + ":" + md5(sign); }
/** * 连接签名方法 * * @param conn 连接 * @param uri 请求地址 * @param length 请求所发Body数据长度 return 签名字符串 */ private String sign(HttpURLConnection conn, String uri, long length) { String sign = conn.getRequestMethod() + "&" + uri + "&" + conn.getRequestProperty("Date") + "&" + length + "&" + password; // System.out.println(sign); // System.out.println("UpYun " + username + ":" + md5(sign)); return "UpYun " + username + ":" + md5(sign); }
@Test public void testSignRequest() throws MalformedURLException { final TwitterAuthConfig config = new TwitterAuthConfig("consumerKey", "consumerSecret"); final TwitterAuthToken accessToken = new TwitterAuthToken("token", "tokenSecret"); final HttpURLConnection connection = mock(HttpURLConnection.class); when(connection.getRequestMethod()).thenReturn("GET"); when(connection.getURL()) .thenReturn(new URL("https://api.twitter.com/1.1/statuses/home_timeline.json")); OAuth1aService.signRequest(config, accessToken, connection, null); verify(connection).setRequestProperty(eq(HttpRequest.HEADER_AUTHORIZATION), any(String.class)); // TODO: Make it so that nonce and timestamp can be specified for testing puproses? }
private void maybeCache() throws IOException { // Are we caching at all? if (!policy.getUseCaches()) return; OkResponseCache responseCache = client.getOkResponseCache(); if (responseCache == null) return; HttpURLConnection connectionToCache = policy.getHttpConnectionToCache(); // Should we cache this response for this request? if (!responseHeaders.isCacheable(requestHeaders)) { responseCache.maybeRemove(connectionToCache.getRequestMethod(), uri); return; } // Offer this request to the cache. cacheRequest = responseCache.put(uri, connectionToCache); }
// set up url, method, header, cookies private void setupFromConnection(HttpURLConnection conn, Connection.Response previousResponse) throws IOException { method = Connection.Method.valueOf(conn.getRequestMethod()); url = conn.getURL(); statusCode = conn.getResponseCode(); statusMessage = conn.getResponseMessage(); contentType = conn.getContentType(); Map<String, List<String>> resHeaders = conn.getHeaderFields(); processResponseHeaders(resHeaders); // if from a redirect, map previous response cookies into this response if (previousResponse != null) { for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) { if (!hasCookie(prevCookie.getKey())) cookie(prevCookie.getKey(), prevCookie.getValue()); } } }
/** * Constructs a canonicalized string for signing a request. * * @param conn the HttpURLConnection to canonicalize * @param accountName the account name associated with the request * @param contentLength the length of the content written to the outputstream in bytes, -1 if * unknown * @param opContext the OperationContext for the given request * @return a canonicalized string. * @throws StorageException */ @Override protected String canonicalize( final HttpURLConnection conn, final String accountName, final Long contentLength, final OperationContext opContext) throws StorageException { if (contentLength < -1) { throw new InvalidParameterException(SR.INVALID_CONTENT_LENGTH); } return canonicalizeHttpRequest( conn.getURL(), accountName, conn.getRequestMethod(), Utility.getStandardHeaderValue(conn, Constants.HeaderConstants.CONTENT_TYPE), contentLength, null, conn, opContext); }
public String startSychronous() { try { mConnection = connection(); mConnection.connect(); if (mConnection.getRequestMethod().equalsIgnoreCase("POST")) { OutputStream out = (OutputStream) mConnection.getOutputStream(); if (mHttpBody != null) { out.write(mHttpBody); } else if (mHttpInputStream != null) { byte[] buffer = new byte[1024]; int len = -1; while ((len = mHttpInputStream.read(buffer)) != -1) { out.write(buffer, 0, len); } mHttpInputStream.close(); out.close(); } } InputStream in = mConnection.getInputStream(); String response = readData(in, mReadCharsetName); mConnection.disconnect(); return response; } catch (IOException e) { e.printStackTrace(); } if (mResponseListener != null) { mResponseListener.OnError("error"); } if (mConnection != null) { mConnection.disconnect(); } return null; }
public static void main(String[] args) { try { // Se obtiene el objeto URL. URL url = new URL("http://getbootstrap.com"); // Se abre la conexión y se hace a HttpURLConnection, ya que es una // conexión HTTP. HttpURLConnection conexion = (HttpURLConnection) url.openConnection(); // Se obtienen los datos de la cabecera de la respuesta y se // muestran por pantalla. // Campos con método get propio. System.out.println("\nCABECERA DE LA RESPUESTA\n"); System.out.println("CAMPOS CON MÉTODO GET PROPIO\n"); System.out.println("Método de petición [getRequestMethod()]: " + conexion.getRequestMethod()); System.out.println("Fecha petición [getDate()]: " + new Date(conexion.getDate())); System.out.println("Código de respuesta [getResponseCode()]: " + conexion.getResponseCode()); System.out.println( "Mensaje de respuesta [getResponseMessage()]: " + conexion.getResponseMessage()); System.out.println( "Fecha última modificación [getLastModified()]: " + new Date(conexion.getLastModified())); System.out.println("Tipo de contenido [getContentType()]: " + conexion.getContentType()); System.out.println("Codificación [getContentEncoding()]: " + conexion.getContentEncoding()); System.out.println( "Tamaño del contenido [getContentLength()]: " + conexion.getContentLength()); System.out.println( "Fecha expiración [getExpiration()]: " + new Date(conexion.getExpiration())); // Todos los campos de la cabecera. System.out.println("\nTODOS LOS CAMPOS DE LA CABECERA DE LA RESPUESTA [getHeaderFields()]\n"); Map<String, List<String>> cabeceraRespuesta = conexion.getHeaderFields(); for (Map.Entry<String, List<String>> campo : cabeceraRespuesta.entrySet()) { System.out.println(campo.getKey() + " : " + campo.getValue()); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public String getRequestMethod() { return _flddelegate.getRequestMethod(); }
public String getMethod() { return connection.getRequestMethod(); }
protected void writeNothing(HttpURLConnection connection) { if (!HttpRequest.NON_PAYLOAD_METHODS.contains(connection.getRequestMethod())) { connection.setRequestProperty(CONTENT_LENGTH, "0"); } }