HttpUrlConnection以GET方式和POST方式请求服务器
HttpUrlConnection以GET方式和POST方式请求服务器
刘付kin 发表于1年前
HttpUrlConnection以GET方式和POST方式请求服务器
  • 发表于 1年前
  • 阅读 3
  • 收藏 0
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

#1:GET方式。这种方式比较简单,直接在URL后面加上参数即可

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class HttpUrlCon {

	public static void main(String[] args) { 
		try {
			
			URL url = new URL("http://localhost:8080/myhome/mypage/JasonTest.do?userName=liufukin");
			HttpURLConnection  httpConn = (HttpURLConnection) url.openConnection();
			   
			// //设置连接属性   
			httpConn.setRequestMethod("GET");// 设置URL请求方法,默认为“GET”
			httpConn.setDoOutput(false);// 禁止 URL 连接进行输出,默认为“false”   
			httpConn.setDoInput(true);// 使用 URL 连接进行输入,默认为“true”   
			httpConn.setUseCaches(false);// 忽略缓存   
			// 设置 《请求头》信息 
			httpConn.setRequestProperty("accept", "*/*");  
			httpConn.setRequestProperty("Content-Type", "application/octet-stream"); //设置的文本类型,此字段必须和和服务器端处理请求流的编码一致,否则无法解析
			httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接   
			httpConn.setRequestProperty("Charset", "UTF-8");
			httpConn.setRequestProperty("BrokerID", URLEncoder.encode("MFTST0", "utf-8"));   
		
			// 前面的操作只是将“请求头”和“正文”组装成request对象,最后真正以HTTP协议发送数据的是下面的getInputStream();
			BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));   
			System.out.println(responseReader.readLine());
			
		}catch (Exception ex) {   
			ex.printStackTrace();   
		}   
	}   
}

#2:POST请求。其实和GET差不多,只是他的参数部分需要以“字符流”的形式处理,在和之前的“请求头”部分信息组装成request对象在发送过去。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class HttpUrlCon {

	public static void main(String[] args) { 
		try {
			
			URL url = new URL("http://localhost:8080/myhome/mypage/JasonTest.do");
			HttpURLConnection  httpConn = (HttpURLConnection) url.openConnection();
			   
			// //设置连接属性   
			httpConn.setRequestMethod("POST");// 设置URL请求方法,默认为“GET”
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出,默认为“false”
			httpConn.setDoInput(true);// 使用 URL 连接进行输入,默认为“true”			httpConn.setUseCaches(false);// 忽略缓存   
			  
			// 设置 《请求头》信息 
			httpConn.setRequestProperty("accept", "*/*");  
			httpConn.setRequestProperty("Content-Type", "application/octet-stream"); //设置的文本类型,此字段必须和和服务器端处理请求流的编码一致,否则无法解析 
			httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接   
			httpConn.setRequestProperty("Charset", "UTF-8");
			httpConn.setRequestProperty("BrokerID", URLEncoder.encode("MFTST0", "utf-8"));   
			
			//发送正文context;其实并非发送,而是将其存储在缓存中,最后和前面设置的“请求头”组装成request对象
			ObjectOutputStream objOutputStrm = new ObjectOutputStream(httpConn.getOutputStream()); 
		    objOutputStrm.writeObject("userName=liufu & pwd=815325"); // 这里发送一个空数据 
		    objOutputStrm.flush(); 
		    objOutputStrm.close(); 
			
			// 前面的操作只是将“请求头”和“正文”组装成request对象,最后真正以HTTP协议发送数据的是下面的getInputStream();
			BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));   
			System.out.println(responseReader.readLine());
			
		}catch (Exception ex) {   
			ex.printStackTrace();   
		}   
	}   
}

#由于经常需要对创建和封装HTTP请求,所以可以把它们整合起来,调用即可产生httpurlconnection对象。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class HttpUrlCon {
	
//	URL url = new URL("http://192.168.7.127:3000/system/brokers?langCode=zh_CN&ordChnl=M");
//	URL url = new URL("http://192.168.7.130:8080/loadrunnerServer/mypage/dologin.do");
//	URL url = new URL("http://192.168.7.127:3000/clients/026200000/session");

	static HashMap<String, String> commonHashmap = new HashMap<String, String>();
	public static void main(String[] args) { 
		HashMap<String, String> hashMapHead = new HashMap<String, String>();//包含“请求头”的信息
		hashMapHead.put("Content-Type", "application/x-www-form-urlencoded");
		hashMapHead.put("Charset", "UTF-8");
		hashMapHead.put("Connection", "Keep-Alive");
		hashMapHead.put("BrokerID", "MFTST0");

		HashMap<String, String> hashMapBody = new HashMap<String, String>();//包含“请求正文(body)”的信息
		hashMapBody.put("password", "123456789");
		hashMapBody.put("ordChnl", "M");
		
		String urlString = "http://192.168.7.127:3000/clients/026200000/session";
		HttpUrlCon httpUrlCon = new HttpUrlCon();
		HttpURLConnection httpURLConn = httpUrlCon.createPOSTHttpconn(urlString, hashMapHead, hashMapBody);
		if(httpURLConn != null){
			BufferedReader bufferedReader = null;
			try {
				if(HttpURLConnection.HTTP_OK == httpURLConn.getResponseCode()){
					bufferedReader = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream(),"UTF-8"));
					if(bufferedReader.readLine().contains("\"status\":\"S\"")){
						commonHashmap.put("authorization", httpURLConn.getHeaderField("authorization"));
						httpUrlCon.getOrders();
					}
				}
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}   
	
	public void getOrders(){
		HashMap<String, String> hashMapHead = new HashMap<String, String>();//包含“请求头”的信息
		hashMapHead.put("Charset", "UTF-8");
		hashMapHead.put("authorization", commonHashmap.get("authorization"));
		hashMapHead.put("BrokerID", "MFTST0");

		HashMap<String, String> hashMapBody = new HashMap<String, String>();//包含“请求正文(body)”的信息
		hashMapBody.put("from", "2012-01-31Z");
		
		String urlString = "http://192.168.7.127:3000/accounts/0262000001011/orders";
		HttpURLConnection httpURLConn = new HttpUrlCon().createGetHttpConn(urlString, hashMapHead, hashMapBody);
		if(httpURLConn != null){
			BufferedReader bufferedReader = null;
			try {
				if(HttpURLConnection.HTTP_OK == httpURLConn.getResponseCode()){
					bufferedReader = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream(),"UTF-8"));
					System.out.println(bufferedReader.readLine());
				}
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	public HttpURLConnection createGetHttpConn(String urlString, HashMap<String, String> hashMapHead, HashMap<String, String> hashMapBody){
		HttpURLConnection  httpConn = null;
		//根据hashMapBody组装需要传给后台的参数,只是以GET的形式发送的话,把他放在URL后面即可
		StringBuffer paramStr = new StringBuffer();
		if(hashMapBody != null){
			Iterator<Map.Entry<String, String>> iterator = hashMapBody.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String, String> entry = iterator.next();
				paramStr.append(entry.getKey()+ "=" + entry.getValue() + "&");
			}
			if(!paramStr.toString().trim().equals("")){
				paramStr.deleteCharAt(paramStr.length()-1);
				urlString += "?" + paramStr;
			}
		}
		try {
			URL url = new URL(urlString);
			httpConn = (HttpURLConnection) url.openConnection();
			// 根据hashMapHead组装《请求头》信息
			if(hashMapHead != null){
				Iterator<Map.Entry<String, String>> iterator = hashMapHead.entrySet().iterator();
				while(iterator.hasNext()){
					Map.Entry<String, String> entry = iterator.next();
					httpConn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
	        return httpConn;
		}catch (Exception ex) {   
			ex.printStackTrace();  
			return null;
		}
	}
	
	
	public HttpURLConnection createPOSTHttpconn(String urlString, HashMap<String, String> hashMapHead, HashMap<String, String> hashMapBody){
		HttpURLConnection  httpConn = null;
		//根据hashMapBody拼接需要发送给后台的正文(body),这个是post形式发送,所以得要用outputstream来发送。
		StringBuffer paramStr = new StringBuffer();
		if(hashMapBody != null){
			Iterator<Map.Entry<String, String>> iterator = hashMapBody.entrySet().iterator();
			while(iterator.hasNext()){
				Map.Entry<String, String> entry = iterator.next();
				paramStr.append(entry.getKey() + "=" + entry.getValue() + "&");
			}
			if(!paramStr.toString().trim().equals("")){
				paramStr.deleteCharAt(paramStr.length()-1);
			}
		}
		try {
			URL url = new URL(urlString);
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性   
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出   ,默认为false
			httpConn.setDoInput(true);// 使用 URL 连接进行输入   ,默认为true
			httpConn.setUseCaches(false);// 忽略缓存   
			httpConn.setRequestMethod("POST");// 设置URL请求方法   
			// 根据hashMapHead组装《请求头》信息
			if(hashMapHead != null){
				Iterator<Map.Entry<String, String>> iterator = hashMapHead.entrySet().iterator();
				while(iterator.hasNext()){
					Map.Entry<String, String> entry = iterator.next();
					httpConn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
			//设置业务逻辑需要传送过去的字段
			DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
	        out.writeBytes(paramStr.toString());
	        out.flush();
	        out.close(); 
	        return httpConn;
		}catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}   
	}
}

#总结:

GET和post主要的差别是一个在URL后面接参数,而另一个是以正文内容的形式发送给服务器端。特别要注意的是:以post方式发起请求的时候,那个“请求头”的hashMapHead.put("Content-Type", "application/x-www-form-urlencoded");一定要和后台服务器的匹配上才行,否则传过去给服务器的参数无法被解析出来,会发现为null。(注意啊!!!)

  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 6
博文 100
码字总数 72832
×
刘付kin
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: