博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【代码积累】URLConnection test
阅读量:4099 次
发布时间:2019-05-25

本文共 5155 字,大约阅读时间需要 17 分钟。

import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.util.Calendar;import net.sf.json.JSONArray;import net.sf.json.JSONObject;public class HttpURLConnectionExample {	private static final String USER_AGENT = "ZTE";		public static void main(String[] args) throws Exception {		HttpURLConnectionExample http = new HttpURLConnectionExample();		System.out.println("Testing 1 - Send Http GET request");		http.sendGet();				System.out.println("\nTesting 2 - Send Http POST request");		http.sendPost();				System.out.println("\nTesting 3- Send Http HEAD request");		http.sendHead();	}		private class HistoryTrack	{		public HistoryTrack()		{			Calendar cal = Calendar.getInstance();			cal.set(2015, 9, 10, 20, 18, 38);			starttime = cal.getTimeInMillis()/1000;						cal.set(2015, 10, 11, 19, 10, 12);			stoptime = cal.getTimeInMillis()/1000;						mdn = new String("13700000000");		}				public long getStarttime() {			return starttime;		}		public void setStarttime(long starttime) {			this.starttime = starttime;		}		public long getStoptime() {			return stoptime;		}		public void setStoptime(long stoptime) {			this.stoptime = stoptime;		}		public String getMdn() {			return mdn;		}		public void setMdn(String mdn) {			this.mdn = mdn;		}		private long starttime;		private long stoptime;		private String mdn;					}		private String generateJson()	{		HistoryTrack historytrack = new HistoryTrack();		//JSONObject jsonObject =  JSONObject.fromObject(historytrack);         //		JSONObject jsonObject = new JSONObject();		jsonObject.put("starttime", String.valueOf(historytrack.getStarttime()) );		jsonObject.put("stoptime", String.valueOf(historytrack.getStoptime()) );		jsonObject.put("mdn", historytrack.getMdn());				//JSONArray array = JSONArray.fromObject(historytrack);				return jsonObject.toString();	}		// HTTP HEAD request		private void sendHead() throws Exception 		{			String url = "http://10.42.205.155/ids/index.html";			URL obj = new URL(url);			HttpURLConnection con = (HttpURLConnection) obj.openConnection();			// optional default is GET			con.setRequestMethod("HEAD");			//add request header			con.setRequestProperty("User-Agent", USER_AGENT);			int responseCode = con.getResponseCode();			System.out.println("\nSending 'HEAD' request to URL : " + url);			System.out.println("Response Code : " + responseCode);			BufferedReader in = new BufferedReader(			        new InputStreamReader(con.getInputStream()));			String inputLine;			StringBuffer response = new StringBuffer();			while ((inputLine = in.readLine()) != null) {				response.append(inputLine);			}			in.close();			//print result			System.out.println(response.toString());		}		// HTTP GET request	private void sendGet() throws Exception 	{		String url = "http://10.42.205.155/ids/index.html";		URL obj = new URL(url);		HttpURLConnection con = (HttpURLConnection) obj.openConnection();		// optional default is GET		con.setRequestMethod("GET");		//add request header		con.setRequestProperty("User-Agent", USER_AGENT);		int responseCode = con.getResponseCode();		System.out.println("\nSending 'GET' request to URL : " + url);		System.out.println("Response Code : " + responseCode);		BufferedReader in = new BufferedReader(		        new InputStreamReader(con.getInputStream()));		String inputLine;		StringBuffer response = new StringBuffer();		while ((inputLine = in.readLine()) != null) {			response.append(inputLine);		}		in.close();		//print result		System.out.println(response.toString());	}			private void sendPost() throws Exception	{		//Construct a URL object		String url = "http://10.42.205.155/ids/index.html";		//String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";		//String urlParameters = "this is a test";		String urlParameters = generateJson();		System.out.println("Body = "+urlParameters);				//Use the URL project to open an http connection(via TCP protocol)		URL obj = new URL(url);		HttpURLConnection con = (HttpURLConnection)obj.openConnection();				//Set method and properties of the http connection		con.setDoOutput(true);  //Allow to send data,default is false		con.setUseCaches(false);		con.setConnectTimeout(10000);		con.setRequestMethod("POST");		con.setRequestProperty("User-Agent", USER_AGENT);		//con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");					//con.connect();				//Use the http connection object's input/output stream to write/read		//Send POST		DataOutputStream wr = new DataOutputStream(con.getOutputStream());		wr.writeBytes(urlParameters);		wr.flush();		wr.close();				//Get response		int responseCode = con.getResponseCode();		System.out.println("\nSending 'POST' request to URL : " + url);		System.out.println("Post parameters : " + urlParameters);		System.out.println("Response Code : " + responseCode);				BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));		String inputLine;		StringBuffer response = new StringBuffer();		while( (inputLine = in.readLine()) != null )		{			response.append(inputLine);		}				in.close();				//print result		System.out.println(response.toString());	}}

转载地址:http://qthii.baihongyu.com/

你可能感兴趣的文章
【Linux】Linux简介以及 与UNIX区别
查看>>
【视频】视频文件格式和视频编码
查看>>
【工具】Notepad++的一些常用配置
查看>>
【文字识别】Python3使用百度AI进行文字识别
查看>>
【图片】图像基本知识以及三原色原理 (rgb)
查看>>
【图片】Python对RGB颜色与16进制颜色进行互转
查看>>
【Python】pyinstaller模块将py文件打包为windows可执行文件exe
查看>>
【自动化】Python3+Selenium3自动化测试-准备工作
查看>>
【Python】pip模块管理Python包的常用方法
查看>>
【数据库】mysql常用的数据类型
查看>>
【Python】base64模块对图片进行base64编码和解码
查看>>
【Python实战】使用python计算多种还款方式的还款计划
查看>>
【视频】视频基本参数介绍
查看>>
【Python】浮点数计算时的不准确性以及如何进行精确计算
查看>>
【Python】pysnooper模块对代码进行调试
查看>>
【股票】股票交易的手续费介绍以及计算
查看>>
【Python】常用的数据类型介绍以及它们之间相互转化
查看>>
【Java】使用前准备工作配置环境变量
查看>>
【Maven】Eclipse中的Maven项目安装与配置
查看>>
【Maven】Java项目管理工具
查看>>