【代码积累】URLConnection test

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());
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值