Java Code Examples for java.net.HttpURLConnection#addRequestProperty()
The following examples show how to use
java.net.HttpURLConnection#addRequestProperty() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnmodifiableMaps.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
void doClient(URI uri) throws Exception { HttpURLConnection uc = (HttpURLConnection) uri.toURL().openConnection(); // Test1: getRequestProperties is unmodifiable System.out.println("Check getRequestProperties"); checkUnmodifiable(uc.getRequestProperties()); uc.addRequestProperty("X", "V"); uc.addRequestProperty("X1", "V1"); checkUnmodifiable(uc.getRequestProperties()); int resp = uc.getResponseCode(); check(resp == 200, "Unexpected response code. Expected 200, got " + resp); // Test2: getHeaderFields is unmodifiable System.out.println("Check getHeaderFields"); checkUnmodifiable(uc.getHeaderFields()); // If the implementation does caching, check again. checkUnmodifiable(uc.getHeaderFields()); }
Example 2
Source File: UnmodifiableMaps.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
void doClient(URI uri) throws Exception { HttpURLConnection uc = (HttpURLConnection) uri.toURL().openConnection(); // Test1: getRequestProperties is unmodifiable System.out.println("Check getRequestProperties"); checkUnmodifiable(uc.getRequestProperties()); uc.addRequestProperty("X", "V"); uc.addRequestProperty("X1", "V1"); checkUnmodifiable(uc.getRequestProperties()); int resp = uc.getResponseCode(); check(resp == 200, "Unexpected response code. Expected 200, got " + resp); // Test2: getHeaderFields is unmodifiable System.out.println("Check getHeaderFields"); checkUnmodifiable(uc.getHeaderFields()); // If the implementation does caching, check again. checkUnmodifiable(uc.getHeaderFields()); }
Example 3
Source File: JGoogleAnalyticsTracker.java From Wurst7 with GNU General Public License v3.0 | 6 votes |
private static void dispatchRequest(String argURL, String userAgent) { try { URL url = new URL(argURL); HttpURLConnection connection = (HttpURLConnection)url.openConnection(proxy); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(true); if(userAgent != null) connection.addRequestProperty("User-Agent", userAgent); connection.connect(); int responseCode = connection.getResponseCode(); if(responseCode != HttpURLConnection.HTTP_OK) logger.log(Level.SEVERE, "JGoogleAnalyticsTracker: Error requesting url '" + argURL + "', received response code " + responseCode); else logger.log(Level.CONFIG, "JGoogleAnalyticsTracker: Tracking success for url '" + argURL + "'"); }catch(Exception e) { logger.log(Level.SEVERE, "Error making tracking request", e); } }
Example 4
Source File: HurlStack.java From barterli_android with Apache License 2.0 | 6 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { if (VolleyLog.sDebug) { VolleyLog.v("Request url: %s\nBody: %s", request.getUrl(), new String(body, HTTP.UTF_8)); } connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request .getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 5
Source File: HurlStack.java From AndroidProjects with MIT License | 5 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 6
Source File: HttpConnectStack.java From KJFrameForAndroid with Apache License 2.0 | 5 votes |
/** * 如果有body则添加 */ private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream( connection.getOutputStream()); out.write(body); out.close(); } }
Example 7
Source File: HttpUrlConnectionBuilder.java From AOSP-Kayboard-7.1.2 with Apache License 2.0 | 5 votes |
/** * Builds the {@link HttpURLConnection} instance that can be used to execute the request. * * TODO: Remove @UsedForTesting after this method is actually used. */ @UsedForTesting public HttpURLConnection build() throws IOException { if (mUrl == null) { throw new IllegalArgumentException("A URL must be specified!"); } final HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection(); connection.setConnectTimeout(mConnectTimeoutMillis); connection.setReadTimeout(mReadTimeoutMillis); connection.setUseCaches(mUseCache); switch (mMode) { case MODE_UPLOAD_ONLY: connection.setDoInput(true); connection.setDoOutput(false); break; case MODE_DOWNLOAD_ONLY: connection.setDoInput(false); connection.setDoOutput(true); break; case MODE_BI_DIRECTIONAL: connection.setDoInput(true); connection.setDoOutput(true); break; } for (final Entry<String, String> entry : mHeaderMap.entrySet()) { connection.addRequestProperty(entry.getKey(), entry.getValue()); } if (mContentLength >= 0) { connection.setFixedLengthStreamingMode(mContentLength); } return connection; }
Example 8
Source File: HurlStack.java From DaVinci with Apache License 2.0 | 5 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 9
Source File: HurlStack.java From SimplifyReader with Apache License 2.0 | 5 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 10
Source File: StoreClientImpl.java From lemon with Apache License 2.0 | 5 votes |
public StoreDTO saveStore(String budgetName, DataSource dataSource, String tenantId) throws Exception { String url = baseUrl + path; HttpURLConnection conn = (HttpURLConnection) new URL(url) .openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.setRequestMethod("POST"); RequestConfig requestConfig = new RequestConfig(); requestConfig.setMethod("POST"); requestConfig.setPath(path); requestConfig.setAccessKey(accessKey); requestConfig.setAccessSecret(accessSecret); conn.addRequestProperty("authorization", rpcAuthHelper.generateAuthorizationStore(requestConfig)); conn.setDoOutput(true); IOUtils.copy(dataSource.getInputStream(), conn.getOutputStream()); logger.info(conn.getResponseCode() + " " + conn.getResponseMessage()); InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); } String result = IOUtils.toString(is, "UTF-8"); logger.info("result : {}", result); return null; }
Example 11
Source File: Cxf6319TestCase.java From cxf with Apache License 2.0 | 5 votes |
@Test public void testDeclarationsInEnvelope() throws Exception { Endpoint ep = Endpoint.publish("http://localhost:" + PORT + "/SoapContext/SoapPort", new ServiceImpl()); try { HttpURLConnection httpConnection = getHttpConnection("http://localhost:" + PORT + "/SoapContext/SoapPort/echo"); httpConnection.setDoOutput(true); InputStream reqin = getClass().getResourceAsStream("request.xml"); assertNotNull("could not load test data", reqin); httpConnection.setRequestMethod("POST"); httpConnection.addRequestProperty("Content-Type", "text/xml"); OutputStream reqout = httpConnection.getOutputStream(); IOUtils.copy(reqin, reqout); reqout.close(); int responseCode = httpConnection.getResponseCode(); InputStream errorStream = httpConnection.getErrorStream(); String error = null; if (errorStream != null) { error = IOUtils.readStringFromStream(errorStream); } assertEquals(error, 200, responseCode); } catch (Exception e) { e.printStackTrace(); } finally { ep.stop(); } }
Example 12
Source File: HttpTinyClient.java From rocketmq-all-4.1.0-incubating with Apache License 2.0 | 5 votes |
static private void setHeaders(HttpURLConnection conn, List<String> headers, String encoding) { if (null != headers) { for (Iterator<String> iter = headers.iterator(); iter.hasNext(); ) { conn.addRequestProperty(iter.next(), iter.next()); } } conn.addRequestProperty("Client-Version", MQVersion.getVersionDesc(MQVersion.CURRENT_VERSION)); conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding); String ts = String.valueOf(System.currentTimeMillis()); conn.addRequestProperty("Metaq-Client-RequestTS", ts); }
Example 13
Source File: HttpConnection.java From incubator-tez with Apache License 2.0 | 5 votes |
private void setupConnection() throws IOException { connection = (HttpURLConnection) url.openConnection(); if (sslFactory != null) { try { ((HttpsURLConnection) connection).setSSLSocketFactory(sslFactory .createSSLSocketFactory()); ((HttpsURLConnection) connection).setHostnameVerifier(sslFactory .getHostnameVerifier()); } catch (GeneralSecurityException ex) { throw new IOException(ex); } } // generate hash of the url msgToEncode = SecureShuffleUtils.buildMsgFrom(url); encHash = SecureShuffleUtils.hashFromString(msgToEncode, jobTokenSecret); // put url hash into http header connection.addRequestProperty(SecureShuffleUtils.HTTP_HEADER_URL_HASH, encHash); // set the read timeout connection.setReadTimeout(httpConnParams.readTimeout); // put shuffle version into http header connection.addRequestProperty(ShuffleHeader.HTTP_HEADER_NAME, ShuffleHeader.DEFAULT_HTTP_HEADER_NAME); connection.addRequestProperty(ShuffleHeader.HTTP_HEADER_VERSION, ShuffleHeader.DEFAULT_HTTP_HEADER_VERSION); }
Example 14
Source File: HttpServerTest.java From msf4j with Apache License 2.0 | 5 votes |
@Test public void testListHeaderParam() throws IOException { HttpURLConnection urlConn = request("/test/v1/listHeaderParam", HttpMethod.GET); urlConn.addRequestProperty("name", "name1,name3,name2,name1"); assertEquals(200, urlConn.getResponseCode()); assertEquals("name1,name3,name2,name1", getContent(urlConn)); urlConn.disconnect(); }
Example 15
Source File: JenkinsConnector.java From codenvy with Eclipse Public License 1.0 | 5 votes |
private String doRequest(String requestMethod, String requestUrl, String contentType, String data) throws IOException, ServerException { URL url = new URL(requestUrl + "/job/" + jobName + "/config.xml"); HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); try { String basicAuth = "Basic " + new String(Base64.getEncoder().encode(url.getUserInfo().getBytes())); httpConnection.setRequestProperty("Authorization", basicAuth); httpConnection.setRequestMethod(requestMethod); httpConnection.addRequestProperty(HttpHeaders.CONTENT_TYPE, contentType); httpConnection.setDoOutput(true); if (!isNullOrEmpty(data)) { try (OutputStream outputStream = httpConnection.getOutputStream()) { outputStream.write(data.getBytes()); } } final int responseCode = httpConnection.getResponseCode(); InputStream inputStream = httpConnection.getInputStream(); if ((responseCode / 100) != 2) { InputStream errorStream = httpConnection.getErrorStream(); throw new ServerException( readAndCloseQuietly(errorStream != null ? errorStream : inputStream)); } return readAndCloseQuietly(inputStream); } finally { if (httpConnection != null) { httpConnection.disconnect(); } } }
Example 16
Source File: DocumentTools.java From o2oa with GNU Affero General Public License v3.0 | 4 votes |
public static byte[] toHtml(String fileName, byte[] bytes) throws Exception { String type = FilenameUtils.getExtension(fileName); if(StringUtils.isEmpty(type)){ return null; }else{ type = type.toLowerCase(); } String toHtmlType = "#doc#docx#xls#xlsx#ppt#pptx"; if(toHtmlType.indexOf(type) == -1){ return null; } try { if(!Config.collect().connect()){ return null; } URL serverUrl = new URL(Config.collect().url() + "/o2_collect_assemble/jaxrs/document/to/html"); HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection(); String boundary = "----" + StringTools.uniqueToken(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setUseCaches(false); connection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try (OutputStream out = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out))) { writer.write(twoHyphens + boundary); writer.write(CRLF); writer.write("Content-Disposition: form-data; name=\"file\"; filename=\"" + (StringUtils.isEmpty(fileName) ? StringTools.uniqueToken() : fileName) + "\""); writer.write(CRLF); writer.write("Content-Type: " + HttpMediaType.APPLICATION_OCTET_STREAM); writer.write(CRLF); writer.write(CRLF); writer.flush(); out.write(bytes); out.flush(); writer.write(CRLF); writer.write(twoHyphens + boundary); writer.write(CRLF); writer.write("Content-Disposition: form-data; name=\"name\""); writer.write(CRLF); writer.write("Content-Type: " + HttpMediaType.TEXT_PLAIN); writer.write(CRLF); writer.write(CRLF); writer.write(Config.collect().getName()); writer.write(CRLF); writer.write(twoHyphens + boundary); writer.write(CRLF); writer.write("Content-Disposition: form-data; name=\"password\""); writer.write(CRLF); writer.write("Content-Type: " + HttpMediaType.TEXT_PLAIN); writer.write(CRLF); writer.write(CRLF); writer.write(Config.collect().getPassword()); writer.write(CRLF); writer.write(twoHyphens + boundary); writer.write(CRLF); writer.write("Content-Disposition: form-data; name=\"type\""); writer.write(CRLF); writer.write("Content-Type: " + HttpMediaType.TEXT_PLAIN); writer.write(CRLF); writer.write(CRLF); writer.write(type); writer.write(CRLF); writer.write(twoHyphens + boundary); writer.write(twoHyphens); writer.flush(); } String respText = null; try (InputStream in = connection.getInputStream()) { respText = IOUtils.toString(in, DefaultCharset.charset_utf_8); } if (StringUtils.isNotEmpty(respText)) { ActionResponse response = XGsonBuilder.instance().fromJson(respText, ActionResponse.class); WrapString wrap = XGsonBuilder.instance().fromJson(response.getData(), WrapString.class); return Base64.decodeBase64(wrap.getValue()); } } catch (Exception e) { logger.warn(fileName+"-转换html异常:"+e.getMessage()); return null; } return null; }
Example 17
Source File: FirebaseInstallationServiceClient.java From firebase-android-sdk with Apache License 2.0 | 4 votes |
/** * Generates a new auth token for a FID on the FIS Servers by calling FirebaseInstallations API * generateAuthToken method. * * @param apiKey API Key that has access to FIS APIs * @param fid Firebase Installation Identifier * @param projectID Project Id * @param refreshToken a token used to authenticate FIS requests * <ul> * <li>400: return response with status BAD_CONFIG * <li>401: return response with status INVALID_AUTH * <li>403: return response with status BAD_CONFIG * <li>404: return response with status INVALID_AUTH * <li>429: throw FirebaseInstallationsException * <li>500: throw FirebaseInstallationsException * </ul> */ @NonNull public TokenResult generateAuthToken( @NonNull String apiKey, @NonNull String fid, @NonNull String projectID, @NonNull String refreshToken) throws FirebaseInstallationsException { String resourceName = String.format(GENERATE_AUTH_TOKEN_REQUEST_RESOURCE_NAME_FORMAT, projectID, fid); int retryCount = 0; URL url = getFullyQualifiedRequestUri(resourceName); while (retryCount <= MAX_RETRIES) { HttpURLConnection httpURLConnection = openHttpURLConnection(url, apiKey); try { httpURLConnection.setRequestMethod("POST"); httpURLConnection.addRequestProperty("Authorization", "FIS_v2 " + refreshToken); writeGenerateAuthTokenRequestBodyToOutputStream(httpURLConnection); int httpResponseCode = httpURLConnection.getResponseCode(); if (httpResponseCode == 200) { return readGenerateAuthTokenResponse(httpURLConnection); } logFisCommunicationError(httpURLConnection, null, apiKey, projectID); if (httpResponseCode == 401 || httpResponseCode == 404) { return TokenResult.builder().setResponseCode(TokenResult.ResponseCode.AUTH_ERROR).build(); } if (httpResponseCode == 429 || (httpResponseCode >= 500 && httpResponseCode < 600)) { retryCount++; continue; } logBadConfigError(); return TokenResult.builder().setResponseCode(TokenResult.ResponseCode.BAD_CONFIG).build(); } catch (IOException ignored) { retryCount++; } finally { httpURLConnection.disconnect(); } } throw new FirebaseInstallationsException( "Firebase Installations Service is unavailable. Please try again later.", Status.UNAVAILABLE); }
Example 18
Source File: NetworkUtils.java From letv with Apache License 2.0 | 4 votes |
public static void report(String url, String data) { Exception e; Throwable th; LogTool.i(TAG, "report. url(%s), data(%s)", url, data); if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(data)) { HttpURLConnection httpURLConnection = null; PrintWriter printWriter = null; try { httpURLConnection = getHttpURLConnection(url, 10, 10); httpURLConnection.setRequestMethod("POST"); httpURLConnection.addRequestProperty(HttpRequest.PARAM_CHARSET, "utf-8"); httpURLConnection.addRequestProperty("connection", Constants.PAGE_FLAG_CLOSE); httpURLConnection.addRequestProperty(HttpRequest.HEADER_CONTENT_TYPE, HttpRequest.CONTENT_TYPE_FORM); httpURLConnection.setFixedLengthStreamingMode(data.length()); httpURLConnection.setDoOutput(true); PrintWriter printWriter2 = new PrintWriter(httpURLConnection.getOutputStream()); try { printWriter2.write(data.toString()); printWriter2.flush(); if (httpURLConnection.getResponseCode() != 200) { LogTool.w(TAG, "report. abnormal response code(%s), url(%s)", Integer.valueOf(httpURLConnection.getResponseCode()), url); } IOUtils.closeSilently(printWriter2); if (httpURLConnection != null) { try { httpURLConnection.disconnect(); printWriter = printWriter2; return; } catch (Throwable e2) { LogTool.e(TAG, "report. " + e2.toString()); } } printWriter = printWriter2; } catch (Exception e3) { e = e3; printWriter = printWriter2; try { LogTool.e(TAG, "report. %s, url(%s)", e.toString(), url); IOUtils.closeSilently(printWriter); if (httpURLConnection != null) { try { httpURLConnection.disconnect(); } catch (Throwable e22) { LogTool.e(TAG, "report. " + e22.toString()); } } } catch (Throwable th2) { th = th2; IOUtils.closeSilently(printWriter); if (httpURLConnection != null) { try { httpURLConnection.disconnect(); } catch (Throwable e222) { LogTool.e(TAG, "report. " + e222.toString()); } } throw th; } } catch (Throwable th3) { th = th3; printWriter = printWriter2; IOUtils.closeSilently(printWriter); if (httpURLConnection != null) { httpURLConnection.disconnect(); } throw th; } } catch (Exception e4) { e = e4; LogTool.e(TAG, "report. %s, url(%s)", e.toString(), url); IOUtils.closeSilently(printWriter); if (httpURLConnection != null) { httpURLConnection.disconnect(); } } } }
Example 19
Source File: ActivityClient.java From jxapi with Apache License 2.0 | 4 votes |
private String issueProfilePut(String path, String data, HashMap<String, String> etag) throws java.io.IOException { URL url = new URL(this._host.getProtocol(), this._host.getHost(),this._host.getPort(), this._host.getPath()+path); HttpURLConnection conn = initializeConnection(url); conn.setRequestMethod("POST"); // Agent Profile requires either of these headers being sent // If neither are sent it will set If-None-Match to null and exception // will be caught during request if (etag.containsKey("If-Match")){ conn.addRequestProperty("If-Match", etag.get("If-Match")); } else{ conn.addRequestProperty("If-None-Match", etag.get("If-None-Match")); } conn.setRequestMethod("PUT"); OutputStreamWriter writer = new OutputStreamWriter( conn.getOutputStream()); try { writer.write(data); } catch (IOException ex) { InputStream s = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(s); BufferedReader br = new BufferedReader(isr); try { String line; while((line = br.readLine()) != null){ System.out.print(line); } System.out.println(); } finally { s.close(); } throw ex; } finally { writer.close(); } try { return readFromConnection(conn); } finally { conn.disconnect(); } }
Example 20
Source File: HurlStack.java From SaveVolley with Apache License 2.0 | 4 votes |
@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()); 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. SaveProtocolVersion saveProtocolVersion = HurlProtocolVersionAdapter.getInstance() .adaptiveProtocolVersion(null); 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."); } SaveStatusLine responseStatus = HurlStatusLineAdapter.getInstance() .adaptiveStatusLine( HurlProtocolVersionAdapter.getInstance(), connection); SaveHttpResponse saveHttpResponse = new SaveHttpResponse(responseStatus); if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) { saveHttpResponse.setEntity( HurlHttpEntityAdapter.getInstance().adaptiveEntity(connection)); } HurlHeaderAdapter.getInstance().adaptiveHeader(saveHttpResponse, connection); return saveHttpResponse; }