/** * Login with user name and password sent as String parameter to url using POST Interrogation * * @param username * @param userpass * @throws IOException */ @And("^I make post message with user: \"([^\"]*)\" and password: \"([^\"]*)\"$") public void HttpPostForm(String username, String userpass) throws IOException { URL url = new URL("http://dippy.trei.ro"); HttpURLConnection hConnection = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); hConnection.setDoOutput(true); hConnection.setRequestMethod("POST"); PrintStream ps = new PrintStream(hConnection.getOutputStream()); ps.print("user="******"&pass="******";do_login=Login"); ps.close(); hConnection.connect(); if (HttpURLConnection.HTTP_OK == hConnection.getResponseCode()) { InputStream is = hConnection.getInputStream(); System.out.println("!!! encoding: " + hConnection.getContentEncoding()); System.out.println("!!! message: " + hConnection.getResponseMessage()); is.close(); hConnection.disconnect(); } }
public void run() { try { Thread.sleep(10); byte[] buf = getBuf(); URL url = new URL("http://127.0.0.1:" + port + "/test"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty( "Content-Type", "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\""); OutputStream out = con.getOutputStream(); out.write(buf); out.close(); InputStream in = con.getInputStream(); byte[] newBuf = readFully(in); in.close(); if (buf.length != newBuf.length) { System.out.println("Doesn't match"); error = true; } synchronized (lock) { ++received; if ((received % 1000) == 0) { System.out.println("Received=" + received); } } } catch (Exception e) { // e.printStackTrace(); System.out.print("."); error = true; } }
private HttpURLConnection prepareOutputConnection() throws IOException { URL url = new URL(Constants.PROTOCOL, host, port, Constants.CONTEXT_PATH); HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection()); connection.setRequestMethod(Constants.REQUEST_METHOD_POST); connection.setDoOutput(true); return connection; }
/** * Method to update database on the server with new and changed hazards given as a JSONObject * instance * * @param uploadHazards A JSONObject instance with encoded new and update hazards * @throws IOException */ public static void uploadHazards(JSONObject uploadHazards) throws IOException { // upload hazards in json to php (to use json_decode) // Hazard parameter should be encoded as json already // Set Post connection URL url = new URL(site + "/update.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestMethod("POST"); OutputStream writer = conn.getOutputStream(); writer.write( uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString // no white space writer.close(); // read response (success / error) BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer response = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); }
/** * Method to return a set of hazard data within CACHE_DISTANCE of given location * * @param location An instance of Location that stores latitude and longitude data * @return JSONObject an instance of JSONObject with json encoded hazard data * @throws IOException * @throws JSONException */ public static JSONObject getHazards(LatLng location) throws IOException, JSONException { // request hazards from long / lat data and retrieve json hazards // tested and working! String longitude = String.valueOf(location.longitude); String latitude = String.valueOf(location.latitude); String query = String.format("longitude=%s&latitude=%s", longitude, latitude); // encode the post query // Set a POST connection URL url = new URL(site + "/request.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); System.out.println(query); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); // Send post request OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(query); writer.flush(); writer.close(); BufferedReader response = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer hazards = new StringBuffer(); String inputLine; while ((inputLine = response.readLine()) != null) { hazards.append(inputLine); } response.close(); return new JSONObject(hazards.toString()); }
/** * 请求xml数据 * * @param url * @param soapAction * @param xml * @return */ public static String sendXMl(String url, String soapAction, String xml) { HttpURLConnection conn = null; InputStream in = null; InputStreamReader isr = null; OutputStream out = null; StringBuffer result = null; try { byte[] sendbyte = xml.getBytes("UTF-8"); URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); conn.setRequestProperty("SOAPAction", soapAction); conn.setRequestProperty("Content-Length", sendbyte.length + ""); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); out = conn.getOutputStream(); out.write(sendbyte); if (conn.getResponseCode() == 200) { result = new StringBuffer(); in = conn.getInputStream(); isr = new InputStreamReader(in, "UTF-8"); char[] c = new char[1024]; int a = isr.read(c); while (a != -1) { result.append(new String(c, 0, a)); a = isr.read(c); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } try { if (in != null) { in.close(); } if (isr != null) { isr.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return result == null ? null : result + ""; }
private String postResult(String URL) { StringBuffer sb = new StringBuffer(); try { String finalUrl = ""; String[] parsedUrl = URL.split("\\?"); String params = URLEncoder.encode(parsedUrl[1], "UTF-8").replace("%3D", "=").replace("%26", "&"); URL url = new URL(parsedUrl[0] + "?" + params); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + getAccessToken()); conn.setDoOutput(true); DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) redirect = true; } if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", "Bearer " + getAccessToken()); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); } catch (Exception e) { e.printStackTrace(); } return sb.toString(); }
void addBody(HttpURLConnection conn, byte[] content) throws IOException { conn.setRequestProperty(CONTENT_LENGTH, String.valueOf(content.length)); // Set default content type if none is set. if (conn.getRequestProperty(CONTENT_TYPE) == null) { conn.setRequestProperty(CONTENT_TYPE, DEFAULT_CONTENT_TYPE); } conn.setDoOutput(true); conn.getOutputStream().write(content); }
private static NameValuePair<Long> poll(Config.HostInfo host, long minAge) throws IOException { NameValuePair<Long> run = null; URL target = new URL(host.url, SERVLET_PATH); HttpURLConnection c; if (host.proxyHost != null) c = (HttpURLConnection) target.openConnection( new Proxy( Proxy.Type.HTTP, new InetSocketAddress(host.proxyHost, host.proxyPort))); else c = (HttpURLConnection) target.openConnection(); try { c.setRequestMethod("POST"); c.setConnectTimeout(2000); c.setDoOutput(true); c.setDoInput(true); PrintWriter out = new PrintWriter(c.getOutputStream()); out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&minage=" + minAge); out.flush(); out.close(); } catch (SocketTimeoutException e) { logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e); throw new IOException("Socket connect timeout"); } int responseCode = c.getResponseCode(); if (responseCode == HttpServletResponse.SC_OK) { InputStream is = c.getInputStream(); // The input is a one liner in the form runId\tAge byte[] buffer = new byte[256]; // Very little cost for this new/GC. int size = is.read(buffer); // We have to close the input stream in order to return it to // the cache, so we get it for all content, even if we don't // use it. It's (I believe) a bug that the content handlers used // by getContent() don't close the input stream, but the JDK team // has marked those bugs as "will not fix." is.close(); StringTokenizer t = new StringTokenizer(new String(buffer, 0, size), "\t\n"); run = new NameValuePair<Long>(); run.name = t.nextToken(); run.value = Long.parseLong(t.nextToken()); } else if (responseCode != HttpServletResponse.SC_NO_CONTENT) { logger.warning("Polling " + target + " got response code " + responseCode); } return run; }
private String transportHttpMessage(String message) { URL serverurl; HttpURLConnection connection; try { serverurl = new URL(this.ServerUrl); connection = (HttpURLConnection) serverurl.openConnection(); connection.setDefaultUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); } catch (Exception e) { e.printStackTrace(); return null; } OutputStreamWriter outstream; try { outstream = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); outstream.write(message); outstream.flush(); /* PrintWriter writer = new PrintWriter(outstream); writer.write(message); writer.flush(); */ outstream.close(); } catch (Exception e) { e.printStackTrace(); return null; } StringBuilder strbuilder = new StringBuilder(); try { InputStreamReader instream = new InputStreamReader(connection.getInputStream(), "UTF-8"); BufferedReader reader = new BufferedReader(instream); String str; while ((str = reader.readLine()) != null) strbuilder.append(str + "\r\n"); instream.close(); } catch (Exception e) { e.printStackTrace(); return null; } connection.disconnect(); return strbuilder.toString(); }
private String getResponse(String link) { try { URL urlObject = new URL(link); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection(); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestProperty("Cookie", cookieValue); return getResponse(httpUrlConnection.getInputStream()); } catch (Exception e) { e.printStackTrace(); } return ""; }
@Override protected TicketItemResponse doInBackground(String... urls) { TicketItemResponse result = null; String uri = GV.URL + "/AddMenuItemToTicketServlet"; try { URL url = new URL(uri); CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("ticketId", String.valueOf(ticketId))); params.add(new BasicNameValuePair("menuItemId", String.valueOf(menuItemId))); params.add(new BasicNameValuePair("userId", String.valueOf(userId))); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); os.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder temp = new StringBuilder(); String inputLine; while ((inputLine = in.readLine()) != null) { temp.append((inputLine)); } in.close(); result = new Gson().fromJson(temp.toString(), TicketItemResponse.class); } catch (Exception e) { e.printStackTrace(); } return result; }
public File download(String songId) { try { String maxRate = getMaxRate(songId); JSONObject songInfo = getSongInfo(songId); // 以歌手名字+歌曲名称组成文件名,格式:歌手 - 歌曲名称 String filename = songInfo.getString("artistName") + " - " + songInfo.getString("songName"); String link = "http://yinyueyun.baidu.com/data/cloud/downloadsongfile?songIds=" + songId + "&rate=" + maxRate; URL urlObject = new URL(link); HttpURLConnection httpUrlConnection = (HttpURLConnection) urlObject.openConnection(); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.setDoOutput(true); httpUrlConnection.setRequestProperty("Cookie", cookieValue); String disposition = httpUrlConnection.getHeaderField("Content-Disposition"); disposition = disposition.replaceAll("\"", ""); // 此转码经测试发现有些是UTF-8编码,有些是GBK编码,所以文件名采用另外方式获得 // disposition = new String(disposition.getBytes("iso-8859-1"),"UTF-8"); // 根据disposition中信息确定歌曲格式 String suffix = disposition.substring(disposition.lastIndexOf(".")); // System.out.println(disposition); InputStream inputStream = httpUrlConnection.getInputStream(); File file = new File(downloadDirectory + "/" + filename + suffix); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[4096]; int read = 0; while ((read = inputStream.read(buf)) > 0) { fos.write(buf, 0, read); } fos.flush(); fos.close(); inputStream.close(); // System.out.println("完成<"+file.getName()+">歌曲下载!"); return file; } catch (Exception e) { e.printStackTrace(); return null; } }
// добавить продукт в базу json server public static void add(ProductREST product) throws NotValidProductException, IOException { try { check(product); // рповеряем продукт // connection к серверу HttpURLConnection con = (HttpURLConnection) ((new URL(PRODUCT_URL).openConnection())); con.setRequestMethod("POST"); // метод post для добавления // генерируем запрос StringBuilder urlParameters = new StringBuilder(); urlParameters .append("name=") .append(URLEncoder.encode(product.getName(), "UTF8")) .append("&"); urlParameters.append("price=").append(product.getPrice()).append("&"); urlParameters.append("weight=").append(product.getWeight()).append("&"); urlParameters .append("manufacturer=") .append(product.getManufacturer().getCountry()) .append("&"); urlParameters.append("category=").append(URLEncoder.encode(product.getCategory(), "UTF8")); con.setDoOutput(true); // разрешаем отправку данных // отправляем try (DataOutputStream out = new DataOutputStream(con.getOutputStream())) { out.writeBytes(urlParameters.toString()); } // код ответа int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + PRODUCT_URL); System.out.println("Response Code : " + responseCode); } catch (NotValidProductException e) { e.printStackTrace(); throw e; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new UnsupportedEncodingException("cannot recognize encoding"); } catch (ProtocolException e) { e.printStackTrace(); throw new ProtocolException("No such protocol, protocol must be POST,DELETE,PATCH,GET etc."); } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("Url is not valid"); } catch (IOException e) { e.printStackTrace(); throw new IOException("cannot write information to server"); } }
/** * 通过post方式访问短信接口 * * @param param sms message, like key1=value1&key2=value2 * @param isproxy 是否启用代理模式 * @return */ public String sendPost(String param, boolean isproxy) { OutputStreamWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(this.url); HttpURLConnection conn = null; conn = (HttpURLConnection) realUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); // POST方法 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty( "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.connect(); out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); out.write(param); out.flush(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("[ERROR]发送 POST 请求出现异常!" + e); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
private static File download(Config.HostInfo host, NameValuePair<Long> run) throws IOException { File jarFile = null; FileOutputStream jarOut = null; URL target = new URL(host.url, SERVLET_PATH); HttpURLConnection c = null; try { c = (HttpURLConnection) target.openConnection(); c.setRequestMethod("POST"); c.setConnectTimeout(2000); c.setDoOutput(true); c.setDoInput(true); PrintWriter out = new PrintWriter(c.getOutputStream()); out.write("host=" + Config.FABAN_HOST + "&key=" + host.key + "&runid=" + run.name); out.flush(); out.close(); } catch (SocketTimeoutException e) { logger.log(Level.WARNING, "Timeout trying to connect to " + target + '.', e); throw new IOException("Socket connect timeout"); } int responseCode = c.getResponseCode(); if (responseCode == HttpServletResponse.SC_OK) { InputStream is = c.getInputStream(); // We allocate in every method instead of a central buffer // to allow concurrent downloads. This can be expanded to use // buffer pools to avoid GC, if necessary. byte[] buffer = new byte[8192]; int size; while ((size = is.read(buffer)) != -1) { if (size > 0 && jarFile == null) { jarFile = new File(Config.TMP_DIR, host.name + '.' + run.name + ".jar"); jarOut = new FileOutputStream(jarFile); } jarOut.write(buffer, 0, size); } is.close(); jarOut.flush(); jarOut.close(); } else { logger.warning( "Downloading run " + run.name + " from " + target + " got response code " + responseCode); } return jarFile; }
private byte[] sendHttpMessage(byte[] body) throws IOException { HttpMessageContext context = HttpMessageContext.getInstance(); context.Debug("GNHttpConnection [sendHttpMessage] starts"); if (context.getLogheader()) { context.Info(logMessageSetting()); } connection.setDoInput(true); if (body != null) { connection.setDoOutput(true); OutputStream os = TimedURLConnection.getOutputStream(connection, timeout * 1000); context.Debug("GNHttpConnection [sendHttpMessage] sending message ..."); os.write(body); context.Debug("GNHttpConnection [sendHttpMessage] message sent"); } context.Debug( "GNHttpConnection [sendHttpMessage] TimedURLConnection.getInputStream timeout[" + timeout + " S]"); InputStream is = TimedURLConnection.getInputStream(connection, timeout * 1000); responseCode = connection.getResponseCode(); context.Debug("GNHttpConnection [sendHttpMessage] responseCode[" + responseCode + "]"); responseMessage = HttpMessageContext.getMessage(is); responseheaders = new Hashtable<String, String>(); int no = 0; while (true) { String headerName = connection.getHeaderFieldKey(no); String headerValue = connection.getHeaderField(no); if (headerName != null && headerName.length() > 0) { responseheaders.put(headerName, headerValue); } else { if (headerValue == null || headerValue.length() <= 0) break; } no++; } if (context.getLogheader()) { GTConfigFile head = new GTConfigFile(responseheaders); context.Debug("GNHttpConnection [sendHttpMessage] responseHeader\r\n" + head); context.Debug( "GNHttpConnection [sendHttpMessage] responseMessage\r\n" + new String(getResponseMessage())); context.Info("GNHttpConnection [sendHttpMessage] success for " + url); } else context.Info("GNHttpConnection [sendHttpMessage] success for " + url); return responseMessage; }
public String performPostCall(String requestURL, String param) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); URL url; String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(param); writer.flush(); writer.close(); os.close(); // int responseCode=conn.getResponseCode(); // if (responseCode == HttpURLConnection.HTTP_OK) { String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = br.readLine()) != null) { response += line; } // } // else { // response= null; // } } catch (Exception e) { e.printStackTrace(); } return response; }
/** * 发起查询处理结果请求 * * @param params 请求参数 * @return 请求结果 * @throws IOException */ public Result getResult(Map<String, Object> params) throws IOException { InputStream is = null; HttpURLConnection conn; StringBuilder sb = new StringBuilder(HOST + "result"); sb.append("?"); for (Map.Entry<String, Object> mapping : params.entrySet()) { sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&"); } URL url = new URL(sb.toString().substring(0, sb.length() - 1)); conn = (HttpURLConnection) url.openConnection(); // 设置必要参数 conn.setConnectTimeout(timeout); conn.setRequestMethod("GET"); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("User-Agent", UpYunUtils.VERSION); // 设置时间 conn.setRequestProperty(DATE, getGMTDate()); // 设置签名 conn.setRequestProperty(AUTHORIZATION, sign(params)); // 创建链接 conn.connect(); // 获取返回的信息 Result result = getResp(conn); if (is != null) { is.close(); } if (conn != null) { conn.disconnect(); } return result; }
@Override public HTTPResponse call() throws Exception { final HttpURLConnection hc = (HttpURLConnection) uri.toURL().openConnection(); try { hc.setDoOutput(true); hc.setRequestMethod(method.name()); hc.setRequestProperty(MimeTypes.CONTENT_TYPE, MimeTypes.APP_XML); hc.getOutputStream().write(content); hc.getOutputStream().close(); hc.setReadTimeout(SOCKET_TIMEOUT); while (!stop) { try { return new HTTPResponse(hc.getResponseCode()); } catch (final SocketTimeoutException e) { } } return null; } finally { hc.disconnect(); } }
protected Void doInBackground(Void... params) { String outString; HttpURLConnection c = null; DataOutputStream os = null; outString = scanData.getOwnBSSID(); outString = outString + "\nL\tX\t" + lastLat + "\t" + lastLon + "\n"; try { URL connectURL = new URL("http://www.openwlanmap.org/android/upload.php"); c = (HttpURLConnection) connectURL.openConnection(); if (c == null) { return null; } c.setDoOutput(true); // enable POST c.setRequestMethod("POST"); c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded, *.*"); c.addRequestProperty("Content-Length", "" + outString.length()); os = new DataOutputStream(c.getOutputStream()); os.write(outString.getBytes()); os.flush(); c.getResponseCode(); os.close(); outString = null; os = null; } catch (IOException ioe) { } finally { try { if (os != null) os.close(); if (c != null) c.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } return null; }
/** * When you call this, you post the data, after which it is gone. The post is synchronous. The * function returns after posting and receiving a reply. Get a new data stream with * startDataStream() to make a new post. (You could hold on to the writer, but using it will have * no effect after calling this method.) * * @return HTTP response code, 200 means successful. */ public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException { cdbId = -1; if (dataWriter == null) { throw new IllegalStateException("call startDataStream() and write something first"); } HttpURLConnection connection = (HttpURLConnection) postURL.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); dataWriter.flush(); String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8"); dataWriter = null; connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length)); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.writeBytes(data); out.flush(); out.close(); int responseCode = connection.getResponseCode(); wasSuccessful = (200 == responseCode); InputStream response; if (wasSuccessful) { response = connection.getInputStream(); } else { response = connection.getErrorStream(); } if (response != null) processResponse(response); connection.disconnect(); return responseCode; }
public InputStream upload() throws ResourceUploaderException { try { try { URL url = new URL(target.toString().replaceAll(" ", "%20")); // some authentications screw up without an explicit port number here String protocol = url.getProtocol().toLowerCase(); if (url.getPort() == -1) { int target_port; if (protocol.equals("http")) { target_port = 80; } else { target_port = 443; } try { String str = target.toString().replaceAll(" ", "%20"); int pos = str.indexOf("://"); pos = str.indexOf("/", pos + 4); // might not have a trailing "/" if (pos == -1) { url = new URL(str + ":" + target_port + "/"); } else { url = new URL(str.substring(0, pos) + ":" + target_port + str.substring(pos)); } } catch (Throwable e) { Debug.printStackTrace(e); } } url = AddressUtils.adjustURL(url); try { if (user_name != null) { SESecurityManager.setPasswordHandler(url, this); } for (int i = 0; i < 2; i++) { try { HttpURLConnection con; if (url.getProtocol().equalsIgnoreCase("https")) { // see ConfigurationChecker for SSL client defaults HttpsURLConnection ssl_con = (HttpsURLConnection) url.openConnection(); // allow for certs that contain IP addresses rather than dns names ssl_con.setHostnameVerifier( new HostnameVerifier() { public boolean verify(String host, SSLSession session) { return (true); } }); con = ssl_con; } else { con = (HttpURLConnection) url.openConnection(); } con.setRequestMethod("POST"); con.setRequestProperty( "User-Agent", Constants.AZUREUS_NAME + " " + Constants.AZUREUS_VERSION); con.setDoOutput(true); con.setDoInput(true); OutputStream os = con.getOutputStream(); byte[] buffer = new byte[65536]; while (true) { int len = data.read(buffer); if (len <= 0) { break; } os.write(buffer, 0, len); } con.connect(); int response = con.getResponseCode(); if ((response != HttpURLConnection.HTTP_ACCEPTED) && (response != HttpURLConnection.HTTP_OK)) { throw (new ResourceUploaderException( "Error on connect for '" + url.toString() + "': " + Integer.toString(response) + " " + con.getResponseMessage())); } return (con.getInputStream()); } catch (SSLException e) { if (i == 0) { if (SESecurityManager.installServerCertificates(url) != null) { // certificate has been installed continue; // retry with new certificate } } throw (e); } } throw (new ResourceUploaderException("Should never get here")); } finally { if (user_name != null) { SESecurityManager.setPasswordHandler(url, null); } } } catch (java.net.MalformedURLException e) { throw (new ResourceUploaderException( "Exception while parsing URL '" + target + "':" + e.getMessage(), e)); } catch (java.net.UnknownHostException e) { throw (new ResourceUploaderException( "Exception while initializing download of '" + target + "': Unknown Host '" + e.getMessage() + "'", e)); } catch (java.io.IOException e) { throw (new ResourceUploaderException( "I/O Exception while downloading '" + target + "':" + e.toString(), e)); } } catch (Throwable e) { ResourceUploaderException rde; if (e instanceof ResourceUploaderException) { rde = (ResourceUploaderException) e; } else { rde = new ResourceUploaderException("Unexpected error", e); } throw (rde); } finally { try { data.close(); } catch (Throwable e) { e.printStackTrace(); } } }
/** * 登陆百度,其他方法调用之前需要先登陆 * * @param username * @param password */ public void login(String username, String password) { try { URL url = new URL("http://www.baidu.com/"); HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setRequestMethod("GET"); String cookie1 = httpUrlConnection.getHeaderField("Set-Cookie"); // System.out.println("cookie1:"+cookie1); cookie1 = cookie1.substring(0, 45); url = new URL("https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true"); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setRequestMethod("GET"); httpUrlConnection.setRequestProperty("Cookie", cookie1); // httpUrlConnection.connect(); String cookie2 = httpUrlConnection.getHeaderField("Set-Cookie"); System.out.println("cookie2:" + cookie2); cookie2 = cookie2.substring(0, 11); String response = getResponse(httpUrlConnection.getInputStream()); // System.out.println(response); Pattern pattern = Pattern.compile("token='(\\w+)'"); Matcher matcher = pattern.matcher(response); matcher.find(); String token = matcher.group(1); url = new URL("https://passport.baidu.com/v2/api/?login"); httpUrlConnection = (HttpURLConnection) url.openConnection(); httpUrlConnection.setRequestMethod("POST"); // System.out.println(cookie1+"; "+cookie2); httpUrlConnection.setRequestProperty("Cookie", cookie1 + "; " + cookie2); httpUrlConnection.setDoOutput(true); // System.out.println(token); String querystring = "loginType=1&tpl=mn&token=" + token + "&username="******"&password="******"&mem_pass=on"; httpUrlConnection.getOutputStream().write(querystring.getBytes()); httpUrlConnection.getOutputStream().flush(); httpUrlConnection.getOutputStream().close(); response = getResponse(httpUrlConnection.getInputStream()); // System.out.println(response); // String cookie3=httpUrlConnection.getHeaderField("Set-Cookie"); // System.out.println("cookie3:"+cookie3); // 获取登陆后的cookie Map<String, List<String>> hfs = httpUrlConnection.getHeaderFields(); List<String> loginCookies = hfs.get("Set-Cookie"); for (String cookie : loginCookies) { cookieValue += cookie.substring(0, cookie.indexOf(";") + 1); } } catch (Exception e) { e.printStackTrace(); } }
/** * This calls the external Moodle web service. * * <p>params String containing the parameters of the call.<br> * elements NodeList containing name/value pairs of returned XML data. * * @param params String * @return elements NodeList * @throws MoodleRestException */ public static NodeList call(String params) throws MoodleRestException { NodeList elements = null; try { URL getUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept", "application/xml"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(params); writer.flush(); writer.close(); // Used for testing StringBuilder buffer = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line = reader.readLine(); buffer.append(line).append('\n'); // FindPath fp=new FindPath(); InputStream resource = ClassLoader.getSystemClassLoader() .getResourceAsStream("net/beaconhillcott/moodlerest/EntityInjection.xml"); BufferedReader entities = new BufferedReader(new InputStreamReader(/*fp.*/ resource)); String entitiesLine = null; while ((entitiesLine = entities.readLine()) != null) { // System.out.println(entitiesLine); buffer.append(entitiesLine).append('\n'); } entities.close(); boolean error = false; while ((line = reader.readLine()) != null) { // System.out.println(line); if (error) throw new MoodleRestException( line.substring(line.indexOf('>') + 1, line.indexOf('<', line.indexOf('>') + 1))); if (line.contains("<EXCEPTION")) error = true; buffer.append(line).append('\n'); } reader.close(); if (debug) { System.out.println(buffer.toString()); } XPath xpath = XPathFactory.newInstance().newXPath(); // InputSource source=new InputSource(connection.getInputStream()); InputSource source = new InputSource(new ByteArrayInputStream(buffer.toString().getBytes())); elements = (NodeList) xpath.evaluate("//VALUE", source, XPathConstants.NODESET); // Used for testing if (debug) { for (int i = 0; i < elements.getLength(); i++) { String parent = elements .item(i) .getParentNode() .getParentNode() .getParentNode() .getParentNode() .getNodeName(); if (parent.equals("KEY")) parent = elements .item(i) .getParentNode() .getParentNode() .getParentNode() .getParentNode() .getAttributes() .getNamedItem("name") .getNodeValue(); String content = elements.item(i).getTextContent(); String nodeName = elements.item(i).getParentNode().getAttributes().getNamedItem("name").getNodeValue(); System.out.println("parent=" + parent + " nodeName=" + nodeName + " content=" + content); } } connection.disconnect(); } catch (XPathExpressionException ex) { Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MoodleCallRestWebService.class.getName()).log(Level.SEVERE, null, ex); } return elements; }
private void addingProperties(final HttpURLConnection connection) throws ProtocolException { connection.setDoOutput(true); connection.setRequestProperty("Content-type", "text/xml"); connection.setRequestProperty("Accept", "text/xml, application/xml"); connection.setRequestMethod("POST"); }
public static String httpPost(String urlAddress, String[] params) { URL url = null; HttpURLConnection conn = null; BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { url = new URL(urlAddress); conn = (HttpURLConnection) url.openConnection(); // 建立连接 // 设置通用的请求属性 /* * conn.setRequestProperty("user-agent", * "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); */ conn.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) "); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setUseCaches(false); conn.setDoInput(true); // conn.setConnectTimeout(5 * 1000); conn.setDoOutput(true); conn.setRequestMethod("POST"); String paramsTemp = ""; for (String param : params) { if (param != null && !"".equals(param)) { if (params.length > 1) { paramsTemp += "&" + param; } else if (params.length == 1) { paramsTemp = params[0]; } } } byte[] b = paramsTemp.getBytes(); System.out.println("btye length:" + b.length); // conn.setRequestProperty("Content-Length", // String.valueOf(b.length)); conn.getOutputStream().write(b, 0, b.length); conn.getOutputStream().flush(); conn.getOutputStream().close(); int count = conn.getResponseCode(); if (200 == count) { in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 发送请求 } else { System.out.println("错误类型:" + count); return "server no start-up"; } while (true) { String line = in.readLine(); if (line == null) { break; } else { sb.append(line); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { System.out.println("error ioexception:" + e.getMessage()); e.printStackTrace(); return "server no start-up"; } finally { try { if (in != null) { in.close(); } if (conn != null) { conn.disconnect(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return sb.toString(); }
SOAPMessage post(SOAPMessage message, URL endPoint) throws SOAPException { boolean isFailure = false; URL url = null; HttpURLConnection httpConnection = null; int responseCode = 0; try { if (endPoint.getProtocol().equals("https")) // if(!setHttps) initHttps(); // Process the URL JaxmURI uri = new JaxmURI(endPoint.toString()); String userInfo = uri.getUserinfo(); url = endPoint; if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri); // TBD // Will deal with https later. if (!url.getProtocol().equalsIgnoreCase("http") && !url.getProtocol().equalsIgnoreCase("https")) { log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https"); throw new IllegalArgumentException( "Protocol " + url.getProtocol() + " not supported in URL " + url); } httpConnection = (HttpURLConnection) createConnection(url); httpConnection.setRequestMethod("POST"); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setUseCaches(false); httpConnection.setInstanceFollowRedirects(true); if (message.saveRequired()) message.saveChanges(); MimeHeaders headers = message.getMimeHeaders(); Iterator it = headers.getAllHeaders(); boolean hasAuth = false; // true if we find explicit Auth header while (it.hasNext()) { MimeHeader header = (MimeHeader) it.next(); String[] values = headers.getHeader(header.getName()); if (values.length == 1) httpConnection.setRequestProperty(header.getName(), header.getValue()); else { StringBuffer concat = new StringBuffer(); int i = 0; while (i < values.length) { if (i != 0) concat.append(','); concat.append(values[i]); i++; } httpConnection.setRequestProperty(header.getName(), concat.toString()); } if ("Authorization".equals(header.getName())) { hasAuth = true; log.fine("SAAJ0091.p2p.https.auth.in.POST.true"); } } if (!hasAuth && userInfo != null) { initAuthUserInfo(httpConnection, userInfo); } OutputStream out = httpConnection.getOutputStream(); message.writeTo(out); out.flush(); out.close(); httpConnection.connect(); try { responseCode = httpConnection.getResponseCode(); // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { isFailure = true; } // else if (responseCode != HttpURLConnection.HTTP_OK) // else if (!(responseCode >= HttpURLConnection.HTTP_OK && responseCode < 207)) else if ((responseCode / 100) != 2) { log.log( Level.SEVERE, "SAAJ0008.p2p.bad.response", new String[] {httpConnection.getResponseMessage()}); throw new SOAPExceptionImpl( "Bad response: (" + responseCode + httpConnection.getResponseMessage()); } } catch (IOException e) { // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds! responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { isFailure = true; } else { throw e; } } } catch (SOAPException ex) { throw ex; } catch (Exception ex) { log.severe("SAAJ0009.p2p.msg.send.failed"); throw new SOAPExceptionImpl("Message send failed", ex); } SOAPMessage response = null; if (responseCode == HttpURLConnection.HTTP_OK || isFailure) { try { MimeHeaders headers = new MimeHeaders(); String key, value; // Header field 0 is the status line so we skip it. int i = 1; while (true) { key = httpConnection.getHeaderFieldKey(i); value = httpConnection.getHeaderField(i); if (key == null && value == null) break; if (key != null) { StringTokenizer values = new StringTokenizer(value, ","); while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim()); } i++; } InputStream httpIn = (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream()); byte[] bytes = readFully(httpIn); int length = httpConnection.getContentLength() == -1 ? bytes.length : httpConnection.getContentLength(); // If no reply message is returned, // content-Length header field value is expected to be zero. if (length == 0) { response = null; log.warning("SAAJ0014.p2p.content.zero"); } else { ByteInputStream in = new ByteInputStream(bytes, length); response = messageFactory.createMessage(headers, in); } httpIn.close(); httpConnection.disconnect(); } catch (SOAPException ex) { throw ex; } catch (Exception ex) { log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex); throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage()); } } return response; }
SOAPMessage doGet(URL endPoint) throws SOAPException { boolean isFailure = false; URL url = null; HttpURLConnection httpConnection = null; int responseCode = 0; try { /// Is https GET allowed?? if (endPoint.getProtocol().equals("https")) initHttps(); // Process the URL JaxmURI uri = new JaxmURI(endPoint.toString()); String userInfo = uri.getUserinfo(); url = endPoint; if (dL > 0) d("uri: " + userInfo + " " + url + " " + uri); // TBD // Will deal with https later. if (!url.getProtocol().equalsIgnoreCase("http") && !url.getProtocol().equalsIgnoreCase("https")) { log.severe("SAAJ0052.p2p.protocol.mustbe.http.or.https"); throw new IllegalArgumentException( "Protocol " + url.getProtocol() + " not supported in URL " + url); } httpConnection = (HttpURLConnection) createConnection(url); httpConnection.setRequestMethod("GET"); httpConnection.setDoOutput(true); httpConnection.setDoInput(true); httpConnection.setUseCaches(false); httpConnection.setFollowRedirects(true); httpConnection.connect(); try { responseCode = httpConnection.getResponseCode(); // let HTTP_INTERNAL_ERROR (500) through because it is used for SOAP faults if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { isFailure = true; } else if ((responseCode / 100) != 2) { log.log( Level.SEVERE, "SAAJ0008.p2p.bad.response", new String[] {httpConnection.getResponseMessage()}); throw new SOAPExceptionImpl( "Bad response: (" + responseCode + httpConnection.getResponseMessage()); } } catch (IOException e) { // on JDK1.3.1_01, we end up here, but then getResponseCode() succeeds! responseCode = httpConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) { isFailure = true; } else { throw e; } } } catch (SOAPException ex) { throw ex; } catch (Exception ex) { log.severe("SAAJ0012.p2p.get.failed"); throw new SOAPExceptionImpl("Get failed", ex); } SOAPMessage response = null; if (responseCode == HttpURLConnection.HTTP_OK || isFailure) { try { MimeHeaders headers = new MimeHeaders(); String key, value; // Header field 0 is the status line so we skip it. int i = 1; while (true) { key = httpConnection.getHeaderFieldKey(i); value = httpConnection.getHeaderField(i); if (key == null && value == null) break; if (key != null) { StringTokenizer values = new StringTokenizer(value, ","); while (values.hasMoreTokens()) headers.addHeader(key, values.nextToken().trim()); } i++; } InputStream httpIn = (isFailure ? httpConnection.getErrorStream() : httpConnection.getInputStream()); // If no reply message is returned, // content-Length header field value is expected to be zero. // java SE 6 documentation says : // available() : an estimate of the number of bytes that can be read // (or skipped over) from this input stream without blocking // or 0 when it reaches the end of the input stream. if ((httpIn == null) || (httpConnection.getContentLength() == 0) || (httpIn.available() == 0)) { response = null; log.warning("SAAJ0014.p2p.content.zero"); } else { response = messageFactory.createMessage(headers, httpIn); } httpIn.close(); httpConnection.disconnect(); } catch (SOAPException ex) { throw ex; } catch (Exception ex) { log.log(Level.SEVERE, "SAAJ0010.p2p.cannot.read.resp", ex); throw new SOAPExceptionImpl("Unable to read response: " + ex.getMessage()); } } return response; }