-
- package tool
-
- class MyHttpUrlConn {
- public static String cookieVal=""
-
- public static void Get(String url_get,String str_param_url,String charset,String cookie) throws IOException {
-
-
- String getURL = url_get + "?" + str_param_url
- URL getUrl = new URL(getURL);
-
-
- HttpURLConnection connection = (HttpURLConnection) getUrl
- .openConnection();
-
- if (cookie != null) {
-
- println("set cookieVal = [" + cookie + "]")
- connection.setRequestProperty("Cookie", cookie);
- }
-
-
-
- connection.connect();
-
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream(),charset));
- System.out.println("Contents of get request:");
- String lines;
- while ((lines = reader.readLine()) != null) {
- System.out.println(lines);
- }
- println(" ")
- reader.close();
-
- connection.disconnect();
- }
-
- public static String Post(String url_post,String str_param_body,String charset,boolean b_flag,String cookies) throws IOException {
-
- URL postUrl = new URL(url_post);
-
- HttpURLConnection connection = (HttpURLConnection) postUrl
- .openConnection();
-
-
-
-
-
-
- if("" != cookies){
- connection.setRequestProperty("Cookie", cookies);
- }
-
- connection.setDoOutput(true);
-
- connection.setDoInput(true);
-
- connection.setRequestMethod("POST");
-
-
- connection.setUseCaches(false);
-
-
-
-
-
-
-
-
-
- connection.setInstanceFollowRedirects(b_flag);
-
-
-
-
-
-
-
- connection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
-
-
- connection.connect();
- DataOutputStream out = new DataOutputStream(connection
- .getOutputStream());
-
-
-
-
-
- println("http param body = [" + str_param_body + "]")
-
- out.writeBytes(str_param_body);
-
- out.flush();
-
-
-
- cookieVal = connection.getHeaderField("Set-Cookie")
- println("get cookieVal = [" + cookieVal + "]")
-
- out.close();
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream(),charset));
- String line;
- System.out.println("Contents of post request:");
- while ((line = reader.readLine()) != null) {
- System.out.println(line);
- }
- println(" ")
-
- reader.close();
- connection.disconnect();
-
- return cookieVal
- }
- }
用法:
String cookie_login = MyHttpUrlConn.Post(URL_LOGIN,"userName=admin&password=12345678","utf-8",false,"");
MyHttpUrlConn.Post(URL_POST_SAVE,"name=mxb&yearsold=6","utf-8",false,cookie_login);MyHttpUrlConn.Get(URL_GET_VIEW,"name=mxb&yearsold=6","utf-8",cookie_login);
说明:
向URL_POST_SAVE Post数据时,要带上URL_LOGIN时生成的cookie,否则无法save数据。
同理Get也是。