List of usage examples for java.net URLConnection setDoOutput
public void setDoOutput(boolean dooutput)
From source file:org.motechproject.mmnaija.web.util.HTTPCommunicator.java
public static String doPost(String serviceUrl, String queryString) { URLConnection connection = null; try {// ww w .java 2 s. c o m URL url = new URL(serviceUrl); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); url = uri.toURL(); // Open the connection connection = url.openConnection(); connection.setDoInput(true); connection.setUseCaches(false); // Disable caching the document connection.setDoOutput(true); // Triggers POST. connection.setRequestProperty("Content-Type", "text/html"); OutputStreamWriter writer = null; log.info("About to write"); try { if (null != connection.getOutputStream()) { writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(queryString); // Write POST query } else { log.warn("connection Null"); } // string. } catch (ConnectException ex) { log.warn("Exception : " + ex); // ex.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (Exception lg) { log.warn("Exception lg: " + lg.toString()); //lg.printStackTrace(); } } } InputStream in = connection.getInputStream(); // StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "utf-8"); String theString = writer.toString(); return theString; } catch (Exception e) { //e.printStackTrace(); log.warn("Error URL " + e.toString()); return ""; } }
From source file:com.jiubang.core.util.HttpUtils.java
/** * Send an HTTP(s) request with POST parameters. * /*from w w w. ja va2 s. c om*/ * @param parameters * @param url * @throws UnsupportedEncodingException * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ static void doPost(Map<?, ?> parameters, URL url) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException { URLConnection cnx = getConnection(url); // Construct data StringBuilder dataBfr = new StringBuilder(); Iterator<?> iKeys = parameters.keySet().iterator(); while (iKeys.hasNext()) { if (dataBfr.length() != 0) { dataBfr.append('&'); } String key = (String) iKeys.next(); dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=') .append(URLEncoder.encode((String) parameters.get(key), "UTF-8")); } // POST data cnx.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream()); Loger.d(LOG_TAG, "Posting crash report data"); wr.write(dataBfr.toString()); wr.flush(); wr.close(); Loger.d(LOG_TAG, "Reading response"); BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream())); String line; while ((line = rd.readLine()) != null) { Loger.d(LOG_TAG, line); } rd.close(); }
From source file:org.acra.HttpUtils.java
/** * Send an HTTP(s) request with POST parameters. * //from w ww.java 2 s.c o m * @param parameters * @param url * @throws UnsupportedEncodingException * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ static void doPost(Map<?, ?> parameters, URL url) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException { URLConnection cnx = getConnection(url); // Construct data StringBuilder dataBfr = new StringBuilder(); Iterator<?> iKeys = parameters.keySet().iterator(); while (iKeys.hasNext()) { if (dataBfr.length() != 0) { dataBfr.append('&'); } String key = (String) iKeys.next(); dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=') .append(URLEncoder.encode((String) parameters.get(key), "UTF-8")); } // POST data cnx.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream()); Log.d(LOG_TAG, "Posting crash report data"); wr.write(dataBfr.toString()); wr.flush(); wr.close(); Log.d(LOG_TAG, "Reading response"); BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream())); String line; while ((line = rd.readLine()) != null) { Log.d(LOG_TAG, line); } rd.close(); }
From source file:com.wareninja.opensource.common.wsrequest.HttpUtils.java
/** * Send an HTTP(s) request with POST parameters. * /* ww w . java 2 s. c om*/ * @param parameters * @param url * @throws UnsupportedEncodingException * @throws IOException * @throws KeyManagementException * @throws NoSuchAlgorithmException */ public static void doPost(Map<?, ?> parameters, URL url) throws UnsupportedEncodingException, IOException, KeyManagementException, NoSuchAlgorithmException { URLConnection cnx = getConnection(url); // Construct data StringBuilder dataBfr = new StringBuilder(); Iterator<?> iKeys = parameters.keySet().iterator(); while (iKeys.hasNext()) { if (dataBfr.length() != 0) { dataBfr.append('&'); } String key = (String) iKeys.next(); dataBfr.append(URLEncoder.encode(key, "UTF-8")).append('=') .append(URLEncoder.encode((String) parameters.get(key), "UTF-8")); } // POST data cnx.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(cnx.getOutputStream()); if (LOGGING.DEBUG) Log.d(LOG_TAG, "Posting crash report data"); wr.write(dataBfr.toString()); wr.flush(); wr.close(); if (LOGGING.DEBUG) Log.d(LOG_TAG, "Reading response"); BufferedReader rd = new BufferedReader(new InputStreamReader(cnx.getInputStream())); String line; int linecount = 0; while ((line = rd.readLine()) != null) { linecount++; if (linecount <= 2) { if (LOGGING.DEBUG) Log.d(LOG_TAG, line); } } rd.close(); }
From source file:com.beyondb.geocoding.BaiduAPI.java
public static Map<String, String> testPost(String x, String y) throws IOException { URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "=" + "&callback=renderReverse&location=" + x + "," + y + "&output=json"); URLConnection connection = url.openConnection(); /**/*from w w w .j a va 2s.com*/ * ??URLConnection?Web * URLConnection???Web??? */ connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); // remember to clean up out.flush(); out.close(); // ????? String res; InputStream l_urlStream; l_urlStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8")); StringBuilder sb = new StringBuilder(""); while ((res = in.readLine()) != null) { sb.append(res.trim()); } String str = sb.toString(); System.out.println(str); Map<String, String> map = null; if (StringUtils.isNotEmpty(str)) { int addStart = str.indexOf("formatted_address\":"); int addEnd = str.indexOf("\",\"business"); if (addStart > 0 && addEnd > 0) { String address = str.substring(addStart + 20, addEnd); map = new HashMap<String, String>(); map.put("address", address); return map; } } return null; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Connects to the server, authenticates the provided username and * password.//www . j av a2 s . co m * * @param username The user's username * @param password The user's password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String accessKey, String base_url) { String token = null; String hash = null; authenticate_log_text = "authenticate()\n"; AUTH_URI = base_url + "/webservice.php"; authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username=" + username + "\n"; Log.d(TAG, "AUTH_URI : "); Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); // =========== get challenge token ============================== ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); try { URL url; // HTTP GET REQUEST url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setUseCaches(false); // for some site that redirects based on user agent con.setInstanceFollowRedirects(true); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15"); con.setAllowUserInteraction(false); int timeout = 20000; con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n"; switch (status) { case 200: case 201: case 302: BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "body : " + sb.toString(); if (status == 302) { authenticate_log_text = sb.toString(); return null; } JSONObject result = new JSONObject(sb.toString()); Log.d(TAG, result.getString("result")); JSONObject data = new JSONObject(result.getString("result")); token = data.getString("token"); break; case 401: Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "Server auth error"; return null; default: Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "connection status code :" + status; return null; } } catch (ClientProtocolException e) { Log.i(TAG, "getchallenge:http protocol error"); Log.e(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n"; return null; } catch (IOException e) { Log.e(TAG, "getchallenge: IO Exception"); Log.e(TAG, e.getMessage()); Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n"; return null; } catch (JSONException e) { Log.i(TAG, "json exception"); authenticate_log_text = authenticate_log_text + "JSon exception\n"; // TODO Auto-generated catch block e.printStackTrace(); return null; } // ================= login ================== try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(token.getBytes()); m.update(accessKey.getBytes()); hash = new BigInteger(1, m.digest()).toString(16); Log.i(TAG, "hash"); Log.i(TAG, hash); } catch (NoSuchAlgorithmException e) { authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n"; e.printStackTrace(); } try { String charset; charset = "utf-8"; String query = String.format("operation=login&username=%s&accessKey=%s", URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset)); authenticate_log_text = authenticate_log_text + "login()\n"; URLConnection connection = new URL(AUTH_URI).openConnection(); connection.setDoOutput(true); // Triggers POST. int timeout = 20000; connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); connection.setUseCaches(false); OutputStream output = connection.getOutputStream(); try { output.write(query.getBytes(charset)); } finally { try { output.close(); } catch (IOException logOrIgnore) { } } Log.d(TAG, "Query written"); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message post body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n"; JSONObject result = new JSONObject(sb.toString()); String success = result.getString("success"); Log.i(TAG, success); if (success == "true") { Log.i(TAG, result.getString("result")); Log.i(TAG, "sucesssfully logged in is"); JSONObject data = new JSONObject(result.getString("result")); sessionName = data.getString("sessionName"); Log.i(TAG, sessionName); authenticate_log_text = authenticate_log_text + "successfully logged in\n"; return token; } else { // success is false, retrieve error JSONObject data = new JSONObject(result.getString("error")); authenticate_log_text = "can not login :\n" + data.toString(); return null; } //token = data.getString("token"); //Log.i(TAG,token); } catch (ClientProtocolException e) { Log.d(TAG, "login: http protocol error"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (IOException e) { Log.d(TAG, "login: IO Exception"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "login: IO Exception \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (JSONException e) { Log.d(TAG, "JSON exception"); // TODO Auto-generated catch block authenticate_log_text = authenticate_log_text + "JSON exception "; authenticate_log_text = authenticate_log_text + e.getMessage(); e.printStackTrace(); } return null; // ======================================================================== }
From source file:com.beyondb.geocoding.BaiduAPI.java
public static String getPointByAddress(String address, String city) throws IOException { String resultPoint = ""; try {/*from w w w. j a v a2s. c o m*/ URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=xml&address=" + address + "&" + city); URLConnection connection = url.openConnection(); /** * ??URLConnection?Web * URLConnection???Web??? */ connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); // remember to clean up out.flush(); out.close(); // ????? String res; InputStream l_urlStream; l_urlStream = connection.getInputStream(); if (l_urlStream != null) { BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8")); StringBuilder sb = new StringBuilder(""); while ((res = in.readLine()) != null) { sb.append(res.trim()); } String str = sb.toString(); System.out.println(str); Document doc = DocumentHelper.parseText(str); // XML Element rootElt = doc.getRootElement(); // ? // System.out.println("" + rootElt.getName()); // ?? Element resultElem = rootElt.element("result"); if (resultElem.hasContent()) { Element locationElem = resultElem.element("location"); Element latElem = locationElem.element("lat"); // System.out.print("lat:"+latElem.getTextTrim()+","); Element lngElem = locationElem.element("lng"); // System.out.println("lng:"+lngElem.getTextTrim()); resultPoint = lngElem.getTextTrim() + "," + latElem.getTextTrim(); } else { System.out.println("can't compute the coor"); resultPoint = " , "; } } else { resultPoint = " , "; } } catch (DocumentException ex) { Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex); } return resultPoint; }
From source file:tkwatch.Utilities.java
/** * Issues a TradeKing API request. Adapted from the <i>TradeKing API * Reference Guide</i>, 03.25.2011, p. 51. * /*from ww w .j a v a 2 s .c om*/ * @param resourceUrl * The URL to which API requests must be made. * @param body * The body of the API request. * @param appKey * The user's application key. * @param userKey * The user's key. * @param userSecret * The user's secret key. * @return Returns the result of the API request. */ public static final String tradeKingRequest(final String resourceUrl, final String body, final String appKey, final String userKey, final String userSecret) { String response = new String(); try { String timestamp = String.valueOf(Calendar.getInstance().getTimeInMillis()); String request_data = body + timestamp; String signature = generateSignature(request_data, userSecret); URL url = new URL(resourceUrl); URLConnection conn = url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "application/xml"); conn.setRequestProperty("Accept", "application/xml"); conn.setRequestProperty("TKI_TIMESTAMP", timestamp); conn.setRequestProperty("TKI_SIGNATURE", signature); conn.setRequestProperty("TKI_USERKEY", userKey); conn.setRequestProperty("TKI_APPKEY", appKey); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes(body); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String temp; while ((temp = in.readLine()) != null) { response += temp + "\n"; } in.close(); return response; } catch (java.security.SignatureException e) { errorMessage(e.getMessage()); return ""; } catch (java.io.IOException e) { errorMessage(e.getMessage()); return ""; } }
From source file:org.intermine.api.mines.FriendlyMineQueryRunner.java
/** * Run a query via the web service//from w ww.jav a 2 s . c o m * * @param urlString url to query * @return reader */ public static BufferedReader runWebServiceQuery(String urlString) { if (StringUtils.isEmpty(urlString)) { return null; } BufferedReader reader = null; try { if (!urlString.contains("?")) { // GET URL url = new URL(urlString); URLConnection conn = url.openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); LOG.info("FriendlyMine URL (GET) " + urlString); } else { // POST String[] params = urlString.split("\\?"); String newUrlString = params[0]; String queryString = params[1]; URL url = new URL(newUrlString); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(queryString); wr.flush(); reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); LOG.info("FriendlyMine URL (POST) " + urlString); } return reader; } catch (Exception e) { LOG.info("Unable to access " + urlString + " exception: " + e.getMessage()); return null; } }
From source file:com.moviejukebox.plugin.OpenSubtitlesPlugin.java
private static String sendRPC(String xml) throws IOException { StringBuilder str = new StringBuilder(); String strona = OS_DB_SERVER; String logowanie = xml;//w w w . jav a 2 s.c om URL url = new URL(strona); URLConnection connection = url.openConnection(); connection.setRequestProperty("Connection", "Close"); // connection.setRequestProperty("Accept","text/html"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(Boolean.TRUE); connection.getOutputStream().write(logowanie.getBytes("UTF-8")); try (Scanner in = new Scanner(connection.getInputStream())) { while (in.hasNextLine()) { str.append(in.nextLine()); } } ((HttpURLConnection) connection).disconnect(); return str.toString(); }