List of usage examples for java.net URLConnection setRequestProperty
public void setRequestProperty(String key, String value)
From source file:org.wso2.esb.integration.common.utils.clients.JSONClient.java
private JSONObject sendRequest(String addUrl, String query) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);//from www. j a v a2 s. c o m connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } JSONObject jsonObject = new JSONObject(out); return jsonObject; }
From source file:org.wso2.esb.integration.common.utils.clients.JSONClient.java
private JSONObject sendRequest(String addUrl, String query, String action) throws IOException, JSONException { String charset = "UTF-8"; URLConnection connection = new URL(addUrl).openConnection(); connection.setDoOutput(true);// www .j a v a2 s .c o m connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("SOAPAction", action); connection.setRequestProperty("Content-Type", "application/json;charset=" + charset); OutputStream output = null; try { output = connection.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException logOrIgnore) { log.error("Error while closing the connection"); } } } InputStream response = connection.getInputStream(); String out = "[Fault] No Response."; if (response != null) { StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int len; while ((len = response.read(bytes)) != -1) { sb.append(new String(bytes, 0, len)); } out = sb.toString(); } JSONObject jsonObject = new JSONObject(out); return jsonObject; }
From source file:org.talend.components.salesforce.connection.oauth.SalesforceOAuthConnection.java
private String getSOAPEndpoint(SalesforceOAuthAccessTokenResponse token, String version) { String endpointURL = null;/*from w w w . java 2 s . c o m*/ BufferedReader reader = null; try { URLConnection idConn = new URL(token.getID()).openConnection(); idConn.setRequestProperty("Authorization", token.getTokenType() + " " + token.getAccessToken()); reader = new BufferedReader(new InputStreamReader(idConn.getInputStream())); JSONParser jsonParser = new JSONParser(); JSONObject json = (JSONObject) jsonParser.parse(reader); JSONObject urls = (JSONObject) json.get("urls"); endpointURL = urls.get("partner").toString().replace("{version}", version); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } return endpointURL; }
From source file:WikiOnThisDay.java
/** * @param month month in the form of integer, eg, 1 corresponds to January, 2 to February * @param date date of the month// w w w . jav a 2 s . co m * @throws JSONException * @throws IOException * @throws XPatherException */ public WikiOnThisDay(int month, int date) throws JSONException, IOException, XPatherException { String[] months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; URL url = new URL("http://wikipedia.org/wiki/" + months[month - 1] + "_" + date); TagNode node; HtmlCleaner cleaner = new HtmlCleaner(); CleanerProperties props = cleaner.getProperties(); props.setAllowHtmlInsideAttributes(true); props.setAllowMultiWordAttributes(true); props.setRecognizeUnicodeChars(true); props.setOmitComments(true); URLConnection conn = url.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17"); InputStreamReader is = new InputStreamReader(conn.getInputStream()); BufferedReader br = new BufferedReader(is); node = cleaner.clean(is); Object[] info_nodes = node.evaluateXPath("//ul"); int eventsNode = 1; if (month == 1 && date == 1) eventsNode++; TagNode EventsNode = (TagNode) info_nodes[eventsNode]; List EventsChildren = EventsNode.getElementListByName("li", false); Events = new JSONArray(); for (int i = 0; i < EventsChildren.size(); i++) { TagNode child = (TagNode) EventsChildren.get(i); String text = child.getText().toString(); String splitby = ""; String[] split = text.split(splitby); JSONObject item = new JSONObject(); item.put("year", split[0].trim()); item.put("text", split[1].trim()); Events.put(item); } TagNode BirthsNode = (TagNode) info_nodes[eventsNode + 1]; List BirthsChildren = BirthsNode.getElementListByName("li", false); Births = new JSONArray(); for (int i = 0; i < BirthsChildren.size(); i++) { TagNode child = (TagNode) BirthsChildren.get(i); String text = child.getText().toString(); String splitby = ""; String[] split = text.split(splitby); JSONObject item = new JSONObject(); item.put("year", split[0].trim()); item.put("text", split[1].trim()); Births.put(item); } TagNode DeathsNode = (TagNode) info_nodes[eventsNode + 2]; List DeathsChildren = DeathsNode.getElementListByName("li", false); Deaths = new JSONArray(); for (int i = 0; i < DeathsChildren.size(); i++) { TagNode child = (TagNode) DeathsChildren.get(i); String text = child.getText().toString(); String splitby = ""; String[] split = text.split(splitby); JSONObject item = new JSONObject(); item.put("year", split[0].trim()); item.put("text", split[1].trim()); Deaths.put(item); } JSONObject data = new JSONObject(); data.put("Deaths", Deaths); data.put("Births", Births); data.put("Events", Events); entireData = new JSONObject(); entireData.put("data", data); entireData.put("url", url.toString()); entireData.put("date", months[month - 1] + " " + date); }
From source file:org.digidoc4j.impl.bdoc.SKTimestampDataLoader.java
@Override public byte[] post(String url, byte[] content) { logger.info("Getting timestamp from " + url); OutputStream out = null;/* w w w .ja v a 2s . c o m*/ InputStream inputStream = null; byte[] result = null; try { URLConnection connection = new URL(url).openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-Type", "application/timestamp-query"); connection.setRequestProperty("Content-Transfer-Encoding", "binary"); connection.setRequestProperty("User-Agent", userAgent); out = connection.getOutputStream(); IOUtils.write(content, out); inputStream = connection.getInputStream(); result = IOUtils.toByteArray(inputStream); } catch (IOException e) { throw new DSSException("An error occured while HTTP POST for url '" + url + "' : " + e.getMessage(), e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(inputStream); } return result; }
From source file:monitoring.tools.AppTweak.java
private JSONObject urlConnection() throws MalformedURLException, IOException { String URI = uri + params.getPackageName() + uriParams; boolean first = true; if (params.getCountry() != null) { URI += "?country=" + params.getCountry(); first = false;/* ww w . j a v a 2s. co m*/ } if (params.getLanguage() != null) { if (first) URI += "?"; else URI += "&"; URI += "language=" + params.getLanguage(); } URLConnection connection = new URL(URI).openConnection(); connection.setRequestProperty("X-Apptweak-Key", token); connection.getInputStream(); return new JSONObject(Utils.streamToString(connection.getInputStream())); }
From source file:it.avalz.opendaylight.controller.Controller.java
private String callControllerApi(String partialUrl) { String authString = this.username + ":" + this.password; StringBuilder responseString = new StringBuilder(); try {// w w w . ja va 2 s .co m URL url = new URL(this.baseUrl + partialUrl); byte[] authEncoded = Base64.encodeBase64(authString.getBytes()); String authEncodedString = new String(authEncoded); URLConnection connection = url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + authEncodedString); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); InputStream is = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line; while ((line = br.readLine()) != null) { responseString.append(line); } br.close(); } catch (Exception e) { e.printStackTrace(); } return responseString.toString(); }
From source file:com.example.android.wearable.wcldemo.pages.StockFragment.java
/** * A simple method that handles making an http request. Although we simplify this example since * we know what type of request is coming in, we leave it at a more generic standing to show * how a more complicated case can be handled. * * @param url The target URL. For GET operations, all the query parameters need to be included * here directly. For POST requests, use the <code>query</code> parameter. * @param method Can be {@link com.google.devrel.wcl.connectivity.WearHttpHelper#METHOD_GET} * or {@link com.google.devrel.wcl.connectivity.WearHttpHelper#METHOD_POST} * @param query Used for POST requests. The format should be * <code>param1=value1¶m2=value2&..</code> * and it <code>value1, value2, ...</code> should all be URLEncoded by the caller. * * @throws IOException/* w w w . jav a 2 s . c om*/ */ private void makeHttpCall(String url, String method, String query, String charset, String nodeId, String requestId) throws IOException { URLConnection urlConnection = new URL(url).openConnection(); urlConnection.setRequestProperty("Accept-Charset", charset); // Note: the following if-clause will not be executed for this particular example if (WearHttpHelper.METHOD_POST.equals(method)) { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); if (!TextUtils.isEmpty(query)) { OutputStream output = urlConnection.getOutputStream(); output.write(query.getBytes(charset)); } } BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuilder sb = new StringBuilder(); while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); int statusCode = ((HttpURLConnection) urlConnection).getResponseCode(); WearManager.getInstance().sendHttpResponse(sb.toString(), statusCode, nodeId, requestId, mResultCallback); }
From source file:org.bireme.interop.fromJson.Json2Couch.java
private void sendDocuments(final String docs) { try {//from w w w . j a v a 2 s .c o m assert docs != null; final URLConnection connection = url.openConnection(); connection.setRequestProperty("CONTENT-TYPE", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()) //final String udocs = URLEncoder.encode(docs, "UTF-8"); ) { out.write(docs); } try (InputStreamReader reader = new InputStreamReader(connection.getInputStream())) { final List<String> msgs = getBadDocuments(reader); for (String msg : msgs) { System.err.println("write error: " + msg); } } } catch (IOException ex) { Logger.getLogger(Json2Couch.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.github.reverseproxy.ReverseProxyJettyHandler.java
private void setHeaders(URLConnection urlConnection, Map<String, String> headers) { for (String key : headers.keySet()) { urlConnection.setRequestProperty(key, headers.get(key)); }/*from w ww.jav a2s . c om*/ }