Java Code Examples for java.net.HttpURLConnection#setRequestProperty()
The following examples show how to use
java.net.HttpURLConnection#setRequestProperty() .
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: Downloader.java From Downloader with Apache License 2.0 | 6 votes |
private void settingHeaders(DownloadTask downloadTask, HttpURLConnection httpURLConnection) { Map<String, String> headers = null; if (null != (headers = downloadTask.getHeaders()) && !headers.isEmpty()) { for (Map.Entry<String, String> entry : headers.entrySet()) { if (TextUtils.isEmpty(entry.getKey()) || TextUtils.isEmpty(entry.getValue())) { continue; } httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue()); } } String eTag = ""; if (!TextUtils.isEmpty((eTag = getEtag()))) { Runtime.getInstance().log(TAG, "Etag:" + eTag); httpURLConnection.setRequestProperty("If-Match", getEtag()); } Runtime.getInstance().log(TAG, "settingHeaders"); }
Example 2
Source File: PreferHeaderForGetAndDeleteITCase.java From olingo-odata4 with Apache License 2.0 | 6 votes |
private HttpURLConnection postRequest(final URL url, final String content, final Map<String, String> headers) throws IOException { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.POST.toString()); for (Map.Entry<String, String> header : headers.entrySet()) { connection.setRequestProperty(header.getKey(), header.getValue()); } connection.setDoOutput(true); final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.append(content); writer.close(); connection.connect(); return connection; }
Example 3
Source File: URLTools.java From MtgDesktopCompanion with GNU General Public License v3.0 | 6 votes |
public static HttpURLConnection getConnection(URL url,String userAgent) throws IOException { Chrono c = new Chrono(); c.start(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); try{ connection.setRequestProperty(USER_AGENT, userAgent); connection.setAllowUserInteraction(true); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("GET"); connection.setReadTimeout(MTGConstants.CONNECTION_TIMEOUT); int status = connection.getResponseCode(); if (!isCorrectConnection(connection) && (status == HttpURLConnection.HTTP_MOVED_TEMP|| status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)) { return getConnection(connection.getHeaderField("Location")); } logger.debug("GET " + url + " : " + connection.getResponseCode() + " [" + c.stopInMillisecond() + "ms]"); } catch(SSLHandshakeException e) { logger.error(url,e); } return connection; }
Example 4
Source File: PseudoWebHDFSConnection.java From Transwarp-Sample-Code with MIT License | 6 votes |
/** * <b>OPEN</b> * * curl -i -L "http://<HOST>:<PORT>/webhdfs/v1/<PATH>?op=OPEN * [&offset=<LONG>][&length=<LONG>][&buffersize=<INT>]" * * @param path * @param os * @throws AuthenticationException * @throws IOException * @throws MalformedURLException */ public String open(String path, OutputStream os) throws MalformedURLException, IOException, AuthenticationException { ensureValidToken(); String spec = MessageFormat.format( "/webhdfs/v1/{0}?op=OPEN&user.name={1}", URLUtil.encodePath(path), this.principal); HttpURLConnection conn = authenticatedURL.openConnection(new URL( new URL(httpfsUrl), spec), token); conn.setRequestMethod("GET"); conn.setRequestProperty("Content-Type", "application/octet-stream"); conn.connect(); InputStream is = conn.getInputStream(); copy(is, os); is.close(); os.close(); String resp = result(conn, false); conn.disconnect(); return resp; }
Example 5
Source File: GnocchiQuery.java From hawkular-alerts with Apache License 2.0 | 6 votes |
private List<Map<String, String>> getAllMetrics() { String allMetricsUrl = baseUrl + "/v1/metric"; try { URL url = new URL(allMetricsUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty(AUTHORIZATION, basicAuth); conn.setRequestMethod(GET); conn.setDoInput(true); List rawAllMetrics = JsonUtil.getMapper().readValue(conn.getInputStream(), List.class); conn.disconnect(); log.debugf("Gnocchi Metrics found %s", rawAllMetrics); return (List<Map<String, String>>) rawAllMetrics; } catch (IOException e) { log.errorf(e,"Error querying Gnocchi metrics %s", allMetricsUrl); } return Collections.EMPTY_LIST; }
Example 6
Source File: BasicHttpITCase.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Test public void testBaseTypeDerivedTypeCasting3() throws Exception { URL url = new URL(SERVICE_URI + "ESTwoPrim(32766)/olingo.odata.test1.ETTwoPrim"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HttpMethod.GET.name()); connection.setRequestProperty(HttpHeader.ACCEPT, "application/json;odata.metadata=full"); connection.connect(); assertEquals(HttpStatusCode.OK.getStatusCode(), connection.getResponseCode()); final String content = IOUtils.toString(connection.getInputStream()); assertTrue(content.contains("\"PropertyInt16\":32766")); assertTrue(content.contains("\"PropertyString\":\"Test String1\"")); assertTrue(content.contains("\"@odata.type\":\"#olingo.odata.test1.ETTwoPrim\"")); }
Example 7
Source File: HttpGets.java From Notebook with Apache License 2.0 | 6 votes |
@Override public void run() { // ignoreHttps(); StringBuffer params = new StringBuffer(); for (Map.Entry<String, String> entry : map.entrySet()) { params.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); } try { HttpURLConnection connection = (HttpURLConnection) new URL(api).openConnection(); connection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"); connection.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); connection.setRequestMethod("GET"); connection.setConnectTimeout(1000 * 30); connection.setReadTimeout(1000 * 30); byte[] datas = readInputStream(connection.getInputStream()); callback.done(datas,null); } catch (Exception e) { callback.done(null, e); } }
Example 8
Source File: ChannelTVHeadendService.java From proxylive with MIT License | 5 votes |
private HttpURLConnection getURLConnection(String request) throws MalformedURLException, IOException { URL tvheadendURL = new URL(config.getSource().getTvheadendURL() + "/" + request); HttpURLConnection connection = (HttpURLConnection) tvheadendURL.openConnection(); connection.setReadTimeout(10000); if (tvheadendURL.getUserInfo() != null) { String basicAuth = "Basic " + new String(Base64.getEncoder().encode(tvheadendURL.getUserInfo().getBytes())); connection.setRequestProperty("Authorization", basicAuth); } connection.setRequestMethod("GET"); connection.connect(); return connection; }
Example 9
Source File: DriveUploader.java From cloud-transfer-backend with MIT License | 5 votes |
private void obtainUploadUrl() throws IOException { user.refreshTokenIfNecessary(); HttpURLConnection connection = (HttpURLConnection) CREATE_FILE_URL.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("User-Agent", USER_AGENT); JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("name", downloadFileInfo.getFileName()); String postBody = jsonObject.toString(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", user.getToken().getTokenType() + " " + user.getToken().getAccessToken()); connection.setRequestProperty("X-Upload-Content-Type", downloadFileInfo.getContentType()); connection.setRequestProperty("X-Upload-Content-Length", String.valueOf(downloadFileInfo.getContentLength())); try (PrintStream writer = new PrintStream(connection.getOutputStream())) { writer.print(postBody); } connection.connect(); int statusCode = connection.getResponseCode(); if (statusCode == HttpStatus.OK.value()) createdFileUrl = new URL(connection.getHeaderField("Location")); else if (statusCode == HttpStatus.UNAUTHORIZED.value()) throw new ApiException(HttpStatus.UNAUTHORIZED, "Your session is expired"); else throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "Cannot create new file in google dirve."); }
Example 10
Source File: HttpHelper.java From barcodescanner-lib-aar with MIT License | 5 votes |
private static CharSequence downloadViaHttp(String uri, String contentTypes, int maxChars) throws IOException { int redirects = 0; while (redirects < 5) { URL url = new URL(uri); HttpURLConnection connection = safelyOpenConnection(url); connection.setInstanceFollowRedirects(true); // Won't work HTTP -> HTTPS or vice versa connection.setRequestProperty("Accept", contentTypes); connection.setRequestProperty("Accept-Charset", "utf-8,*"); connection.setRequestProperty("User-Agent", "ZXing (Android)"); try { int responseCode = safelyConnect(connection); switch (responseCode) { case HttpURLConnection.HTTP_OK: return consume(connection, maxChars); case HttpURLConnection.HTTP_MOVED_TEMP: String location = connection.getHeaderField("Location"); if (location != null) { uri = location; redirects++; continue; } throw new IOException("No Location"); default: throw new IOException("Bad HTTP response: " + responseCode); } } finally { connection.disconnect(); } } throw new IOException("Too many redirects"); }
Example 11
Source File: SyncSender.java From rollbar-java with MIT License | 5 votes |
private HttpURLConnection getConnection() throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(this.proxy); if (accessToken != null && !"".equals(accessToken)) { connection.setRequestProperty("x-rollbar-access-token", accessToken); } connection.setRequestProperty("Accept-Charset", UTF_8); connection.setRequestProperty("Content-Type", "application/json; charset=" + UTF_8); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); connection.setRequestMethod("POST"); return connection; }
Example 12
Source File: UrlNetworkManager.java From Yahala-Messenger with MIT License | 5 votes |
private void handleHeaders(HttpURLConnection conn) { Map<String, String> headers = settings.getHeaders(); if (headers != null) { for (String key : headers.keySet()) { conn.setRequestProperty(key, headers.get(key)); } } }
Example 13
Source File: UndeployProcessOperation.java From bonita-studio with GNU General Public License v2.0 | 5 votes |
protected void deleteProcessDefinition(final ProcessAPI processApi, final long processDefinitionId, String apiToken) throws IOException, MalformedURLException, ProtocolException, DeletionException { final HttpURLConnection deleteConnection = openConnection(getUrlBase() + API_PROCESS_RESOURCE + processDefinitionId); deleteConnection.setRequestMethod(HTTP_METHOD_DELETE); deleteConnection.setRequestProperty(BONITA_API_TOKEN_HEADER, apiToken); if (HttpURLConnection.HTTP_OK != deleteConnection.getResponseCode()) { processApi.deleteProcessDefinition(processDefinitionId); } deleteConnection.disconnect(); }
Example 14
Source File: DataRESTAPI.java From MaximoForgeViewerPlugin with Eclipse Public License 1.0 | 5 votes |
public ResultViewerService viewableQuery( String viewableURN ) throws IOException, URISyntaxException { String scope[] = { SCOPE_DATA_READ }; ResultAuthentication authResult = authenticate( scope ); if( authResult.isError() ) { return new ResultViewerService( authResult ); } viewableURN = new String( Base64.encodeBase64( viewableURN.getBytes() ) ); String params[] = { viewableURN }; String frag = makeURN( API_VIEWING, PATT_VIEW_QUERY, params ); URI uri = new URI( _protocol, null, lookupHostname(), _port, frag, null, null ); URL url = new URL( uri.toASCIIString() ); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod( "GET" ); authResult.setAuthHeader( connection ); connection.setRequestProperty( "Accept", "Application/json" ); return new ResultViewerService( connection ); }
Example 15
Source File: KeycloakServiceClient.java From che with Eclipse Public License 2.0 | 4 votes |
private String doRequest(String url, String method, List<Pair<String, ?>> parameters) throws IOException, ServerException, ForbiddenException, NotFoundException, UnauthorizedException, BadRequestException { final String authToken = EnvironmentContext.getCurrent().getSubject().getToken(); final boolean hasQueryParams = parameters != null && !parameters.isEmpty(); if (hasQueryParams) { final UriBuilder ub = UriBuilder.fromUri(url); for (Pair<String, ?> parameter : parameters) { ub.queryParam(parameter.first, parameter.second); } url = ub.build().toString(); } final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(60000); conn.setReadTimeout(60000); try { conn.setRequestMethod(method); // drop a hint for server side that we want to receive application/json conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); if (authToken != null) { conn.setRequestProperty(HttpHeaders.AUTHORIZATION, "bearer " + authToken); } final int responseCode = conn.getResponseCode(); if ((responseCode / 100) != 2) { InputStream in = conn.getErrorStream(); if (in == null) { in = conn.getInputStream(); } final String str; try (Reader reader = new InputStreamReader(in)) { str = CharStreams.toString(reader); } final String contentType = conn.getContentType(); if (contentType != null && (contentType.startsWith(MediaType.APPLICATION_JSON) || contentType.startsWith("application/vnd.api+json"))) { final KeycloakErrorResponse serviceError = DtoFactory.getInstance().createDtoFromJson(str, KeycloakErrorResponse.class); if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) { throw new ForbiddenException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) { throw new NotFoundException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) { throw new UnauthorizedException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) { throw new ServerException(serviceError.getErrorMessage()); } else if (responseCode == Response.Status.BAD_REQUEST.getStatusCode()) { throw new BadRequestException(serviceError.getErrorMessage()); } throw new ServerException(serviceError.getErrorMessage()); } // Can't parse content as json or content has format other we expect for error. throw new IOException( String.format( "Failed access: %s, method: %s, response code: %d, message: %s", UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str)); } try (Reader reader = new InputStreamReader(conn.getInputStream())) { return CharStreams.toString(reader); } } finally { conn.disconnect(); } }
Example 16
Source File: HttpGateway.java From ict with Apache License 2.0 | 4 votes |
private static void applyRequestProperties(HttpURLConnection connection, Map<String, String> requestProperties) { for(Map.Entry<String, String> requestProperty : requestProperties.entrySet()) connection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue()); }
Example 17
Source File: TimingsExport.java From Nukkit with GNU General Public License v3.0 | 4 votes |
@Override public void run() { this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadStart")); this.out.add("data", JsonUtil.mapToArray(this.history, TimingsHistory::export)); String response = null; try { HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection(); con.setDoOutput(true); con.setRequestProperty("User-Agent", "Nukkit/" + Server.getInstance().getName() + "/" + InetAddress.getLocalHost().getHostName()); con.setRequestMethod("POST"); con.setInstanceFollowRedirects(false); PGZIPOutputStream request = new PGZIPOutputStream(con.getOutputStream()); request.setLevel(Deflater.BEST_COMPRESSION); request.write(new Gson().toJson(this.out).getBytes("UTF-8")); request.close(); response = getResponse(con); if (con.getResponseCode() != 302) { this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadError", new String[]{String.valueOf(con.getResponseCode()), con.getResponseMessage()})); if (response != null) { Server.getInstance().getLogger().alert(response); } return; } String location = con.getHeaderField("Location"); this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsLocation", location)); if (!(this.sender instanceof ConsoleCommandSender)) { Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location)); } if (response != null && !response.isEmpty()) { Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsResponse", response)); } File timingFolder = new File(Server.getInstance().getDataPath() + File.separator + "timings"); timingFolder.mkdirs(); String fileName = timingFolder + File.separator + new SimpleDateFormat("'timings-'yyyy-MM-dd-hh-mm'.txt'").format(new Date()); FileWriter writer = new FileWriter(fileName); writer.write(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsLocation", location) + "\n\n"); writer.write(new GsonBuilder().setPrettyPrinting().create().toJson(this.out)); writer.close(); Server.getInstance().getLogger().info(Server.getInstance().getLanguage().translateString("nukkit.command.timings.timingsWrite", fileName)); } catch (IOException exception) { this.sender.sendMessage(TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError")); if (response != null) { Server.getInstance().getLogger().alert(response); } Server.getInstance().getLogger().logException(exception); } }
Example 18
Source File: MbgaOauthUtil.java From gameserver with Apache License 2.0 | 4 votes |
public static Token getTemporaryToken(MbgaProvider provider, Consumer consumer) { Token token = new Token(); Map<String, Object> map = new TreeMap<String, Object>(); String uri = provider.getRequestTokenEndpoint(); try { // HttpResponse response = httpClient.execute(httppost); URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); String authorization = createOauthHeaderWhenTempToken(uri, consumer.getKey(), consumer.getSecret()); conn.setDoOutput(true); conn.setRequestProperty("Content-Length", "0"); conn.setRequestProperty("Authorization", authorization); conn.setRequestProperty("Content-Type", "application/json; charset=utf8"); conn.getOutputStream().close(); Integer status = conn.getResponseCode();// response.getStatusLine().getStatusCode(); logger.debug("status:{}, authorization:{}", status, authorization); String result = Utils.getStreamAsString(conn.getInputStream());// EntityUtils.toString(response.getEntity()); logger.debug(result); String decodeResult = URLDecoder.decode(result, UTF8); map.putAll(unjoin(decodeResult, "&")); map.put("status", status); token.setToken((String) map.get(OAUTH_TOKEN)); token.setSecret((String) map.get(OAUTH_TOKEN_SECRET)); token.setStatus(status.toString()); if (status != 200) { token.setErrorMessage(result); } return token; } catch (Exception e) { token.setErrorMessage(e.toString()); e.printStackTrace(); return token; } }
Example 19
Source File: WSClientTest.java From cjs_ssms with GNU General Public License v2.0 | 4 votes |
/** * 调用接口:http://blog.csdn.net/u011165335/article/details/51345224 * http://www.cnblogs.com/siqi/archive/2013/12/15/3475222.html * @param args */ public static void main(String[] args) throws IOException { //服务的地址 // URL wsUrl = new URL(EnvEnum.IP9000.getVal()+"wSSample"); URL wsUrl = new URL(EnvEnum.IP8080.getVal()+"webservice/wSSample");/*webservice是web.xml中配置的 tomcat发布接口测试*/ HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); OutputStream os = conn.getOutputStream(); //请求体 String soap = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:q0=\"" + SERVICE_NAMESPACE + "\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" + "<soapenv:Body> <q0:" + METHOD + "><arg0>" + PARAM + "</arg0> </q0:" + METHOD + "> </soapenv:Body> </soapenv:Envelope>"; os.write(soap.getBytes()); InputStream is = conn.getInputStream(); byte[] b = new byte[1024]; int len = 0; String s = ""; while((len = is.read(b)) != -1){ String ss = new String(b,0,len,"UTF-8"); s += ss; } System.out.println(s); /* * 返回请求值 * <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body> * <ns2:sayResponse xmlns:ns2="http://cxf.cjsssmsweb.chengjs.com/"> * <return>Hellochengjs</return> * </ns2:sayResponse> * </soap:Body></soap:Envelope> * */ is.close(); os.close(); conn.disconnect(); }
Example 20
Source File: RelationshipExtractor.java From wex-wdc-integration-samples with MIT License | 4 votes |
@POST public String extract(@FormParam("sid") String sid, @FormParam("text") String text) { if (text==null || "".equals(text)) return ""; //Nothing to do if there is no text String username = "xxx"; String passwd = "xxx"; String post = "xxx"; try { //Get the service endpoint details JSONObject serviceInfo = new JSONObject(System.getenv("VCAP_SERVICES")); JSONObject credentials = serviceInfo.getJSONArray("relationship_extraction").getJSONObject(0).getJSONObject("credentials"); String restServerURL = credentials.getString("url"); username = credentials.getString("username"); passwd = credentials.getString("password"); //Construct the payload that we will send to the service if (sid==null) { // default to English news if no sid provided post = "sid=ie-en-news" + "&txt=" + URLEncoder.encode(text, "UTF-8"); } else { post = "sid=" + URLEncoder.encode(sid, "UTF-8") + "&txt=" + URLEncoder.encode(text, "UTF-8"); } //Prepare the HTTP connection to the service HttpURLConnection conn = (HttpURLConnection)new URL(restServerURL).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String auth = username + ":" + passwd; conn.setRequestProperty("Authorization", "Basic "+Base64.encodeBase64String(auth.getBytes())); DataOutputStream output = new DataOutputStream(conn.getOutputStream()); // make the connection conn.connect(); // post request output.writeBytes(post); output.flush(); output.close(); //Read the response from the service BufferedReader rdr = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); /* if (conn.getResponseCode()==HttpURLConnection.HTTP_OK) System.out.println("Response OK from: "+conn.getURL().toString()); else System.err.println("Unsuccesful response: "+conn.getResponseCode()+ " from: "+conn.getURL().toString()); */ String line = ""; StringBuffer buf = new StringBuffer(); while ((line = rdr.readLine()) != null) { buf.append(line); buf.append("\n"); } rdr.close(); //Return the response from the service return buf.toString(); } catch (Exception e) { //Returning any non-200 HTTP status code from the service might facilitate better error handling... return "used u:"+username +"\np:"+passwd +"\npost:"+post +"\n"+e.toString(); } }