List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:CookieAccessor.java
/** * Sets a custom cookie in request header * Another way to set cookies before recent changes to CookieManager */// w ww. j a v a 2s . c om public void setCookieInURLConn() { try { URL url = new URL("http://host.example.com/"); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", "UserName=John Doe"); System.out.println("Set cookie in URL connection"); } catch (Exception e) { System.out.println("Unable to set cookie in URL connection"); e.printStackTrace(); } }
From source file:com.seleritycorp.common.base.coreservices.RawCoreServiceClient.java
private String getRawResponse(String rawRequest, int timeoutMillis) throws IOException { URLConnection connection = apiUrl.openConnection(); connection.setRequestProperty("Accept", "text/plain"); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestProperty("User-Agent", client); connection.setDoOutput(true);/*from w w w . j a v a2 s . c om*/ connection.setReadTimeout(timeoutMillis); final OutputStream out = connection.getOutputStream(); out.write(rawRequest.getBytes(StandardCharsets.UTF_8)); out.flush(); out.close(); log.debug("wrote request " + rawRequest + " (timeout wanted: " + timeoutMillis + ", actual: " + connection.getReadTimeout() + ")"); String response = null; try (final InputStream in = connection.getInputStream()) { response = IOUtils.toString(in, StandardCharsets.UTF_8); } return response; }
From source file:org.springframework.ide.eclipse.boot.wizard.github.auth.BasicAuthCredentials.java
@Override public void apply(URLConnection conn) { try {/* w ww . ja va2 s . c om*/ if (matchHost(conn.getURL().getHost())) { conn.setRequestProperty("Authorization", computeAuthString()); } } catch (UnsupportedEncodingException e) { //Shouldn't really be possible... BootWizardActivator.log(e); } }
From source file:org.springframework.ide.eclipse.wizard.gettingstarted.github.auth.BasicAuthCredentials.java
@Override public void apply(URLConnection conn) { try {// w ww.j a v a 2s .co m if (matchHost(conn.getURL().getHost())) { conn.setRequestProperty("Authorization", computeAuthString()); } } catch (UnsupportedEncodingException e) { //Shouldn't really be possible... WizardPlugin.log(e); } }
From source file:com.icesoft.faces.renderkit.IncludeRenderer.java
public void encodeBegin(FacesContext context, UIComponent component) throws IOException { if (context == null || component == null) { throw new NullPointerException("Null Faces context or component parameter"); }/* w w w .jav a 2 s . c om*/ // suppress rendering if "rendered" property on the component is // false. if (!component.isRendered()) { return; } String page = (String) component.getAttributes().get("page"); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); URI absoluteURI = null; try { absoluteURI = new URI(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI()); URL includedURL = absoluteURI.resolve(page).toURL(); URLConnection includedConnection = includedURL.openConnection(); includedConnection.setRequestProperty("Cookie", "JSESSIONID=" + ((HttpSession) context.getExternalContext().getSession(false)).getId()); Reader contentsReader = new InputStreamReader(includedConnection.getInputStream()); try { StringWriter includedContents = new StringWriter(); char[] buf = new char[2000]; int len = 0; while ((len = contentsReader.read(buf)) > -1) { includedContents.write(buf, 0, len); } ((UIOutput) component).setValue(includedContents.toString()); } finally { contentsReader.close(); } } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(e.getMessage()); } } super.encodeBegin(context, component); }
From source file:org.wso2.carbon.automation.test.utils.generic.GenericJSONClient.java
public JSONObject doGet(String endpoint, String query, String contentType) throws AutomationFrameworkException, IOException { String charset = "UTF-8"; OutputStream os = null;/*from w w w . j a v a 2 s . com*/ InputStream is = null; try { if (contentType == null || "".equals(contentType)) { contentType = "application/json"; } URLConnection conn = new URL(endpoint).openConnection(); conn.setRequestProperty(GenericJSONClient.HEADER_CONTENT_TYPE, contentType); conn.setRequestProperty(GenericJSONClient.HEADER_ACCEPT_CHARSET, charset); conn.setRequestProperty("Content-Length", "1000"); conn.setReadTimeout(30000); System.setProperty("java.net.preferIPv4Stack", "true"); conn.setRequestProperty("Connection", "close"); conn.setDoOutput(true); os = conn.getOutputStream(); os.write(query.getBytes(charset)); is = conn.getInputStream(); String out = null; if (is != null) { StringBuilder source = new StringBuilder(); byte[] data = new byte[1024]; int len; while ((len = is.read(data)) != -1) { source.append(new String(data, 0, len, Charset.defaultCharset())); } out = source.toString(); } return new JSONObject(out); } catch (IOException e) { throw new AutomationFrameworkException("Error occurred while executing the GET operation", e); } catch (JSONException e) { throw new AutomationFrameworkException("Error occurred while parsing the response to a JSONObject", e); } finally { assert os != null; os.flush(); os.close(); assert is != null; is.close(); } }
From source file:org.sleeksnap.uploaders.url.GoogleShortener.java
@Override public String upload(final URLUpload url) throws Exception { // Sanity check, otherwise google's api returns a 400 if (url.toString().matches("http://goo.gl/[a-zA-Z0-9]{1,10}")) { return url.toString(); }/*from w w w . j a va 2 s.c o m*/ final URLConnection connection = new URL(PAGE_URL).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-type", "application/json"); final JSONObject out = new JSONObject(); out.put("longUrl", url.getURL()); final OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(out.toString()); writer.flush(); writer.close(); final String contents = StreamUtils.readContents(connection.getInputStream()); final JSONObject resp = new JSONObject(contents); if (resp.has("id")) { return resp.getString("id"); } else { throw new UploadException("Unable to find short url"); } }
From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.AkismetCommentValidator.java
public int validate(WeblogEntryComment comment, RollerMessages messages) { StringBuffer sb = new StringBuffer(); sb.append("blog=").append(WebloggerFactory.getWeblogger().getUrlStrategy() .getWeblogURL(comment.getWeblogEntry().getWebsite(), null, true)).append("&"); sb.append("user_ip=").append(comment.getRemoteHost()).append("&"); sb.append("user_agent=").append(comment.getUserAgent()).append("&"); sb.append("referrer=").append(comment.getReferrer()).append("&"); sb.append("permalink=").append(comment.getWeblogEntry().getPermalink()).append("&"); sb.append("comment_type=").append("comment").append("&"); sb.append("comment_author=").append(comment.getName()).append("&"); sb.append("comment_author_email=").append(comment.getEmail()).append("&"); sb.append("comment_author_url=").append(comment.getUrl()).append("&"); sb.append("comment_content=").append(comment.getContent()); try {//from www . ja v a 2s . c o m URL url = new URL("http://" + apikey + ".rest.akismet.com/1.1/comment-check"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("User_Agent", "Roller " + WebloggerFactory.getWeblogger().getVersion()); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8"); conn.setRequestProperty("Content-length", Integer.toString(sb.length())); OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream()); osr.write(sb.toString(), 0, sb.length()); osr.flush(); osr.close(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = br.readLine(); if ("true".equals(response)) { messages.addError("comment.validator.akismetMessage"); return 0; } else return 100; } catch (Exception e) { log.error("ERROR checking comment against Akismet", e); } return 0; // interpret error as spam: better safe than sorry? }
From source file:org.springframework.ide.eclipse.gettingstarted.github.auth.BasicAuthCredentials.java
@Override public void apply(URLConnection conn) { try {//from ww w .ja v a 2s.c om if (matchHost(conn.getURL().getHost())) { conn.setRequestProperty("Authorization", computeAuthString()); } } catch (UnsupportedEncodingException e) { //Shouldn't really be possible... GettingStartedActivator.log(e); } }
From source file:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java
@Override /**/*from w w w. j a v a 2 s .c o m*/ * Run the AuthGetTokeb Web API Method */ public Long execute() { //Build url Parameter String String urlParameters = APIMETHOD + "&username=" + this.username + "&password=" + this.password; //Try to execute the API Method try { URL url = new URL(userAuthentication.getBaseURL()); URLConnection conn = url.openConnection(); //add user agent to the request header conn.setRequestProperty("User-Agent", USER_AGENT); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); //Read the response JSON StringBuilder text = new StringBuilder(); while ((line = reader.readLine()) != null) { text.append(line).append("\n"); } JSONObject json = (JSONObject) new JSONParser().parse(text.toString()); this.status = (Long) json.get("status"); if (this.status != -1L) { this.authToken = (String) json.get("result"); //Save the AuthToken userAuthentication.setAuthToken((String) json.get("result")); } writer.close(); reader.close(); } catch (Exception e) { System.err.println(e.getMessage()); } return this.status; }