关于HTTP的post请求和get请求。

超文本传输协议HTTP的涉及目的是保证客户机与服务器之间的通讯,http的工作方式是客户机与服务器之间的请求-应答协议。web浏览器可能是客户端,而计算机上的网络应用程序也可能作为服务器。举例子:客户端(浏览器)向服务器提交HTTP请求;服务器向客户端反应响应,相应包含关于请求的状态信息以及可能被请求的内容。

请求响应最常用的方法就是GET和POST了。

GET从指定的资源请求数据,是一种将参数附带到url里面。

get请求可被缓存

get请求保留在浏览器历史记录中

get请求可被收藏为书签

get请求不应再处理敏感数据时使用

get请求有长度限制

get请求只应当用于取回数据

POST是向指定的资源提交要被处理的数据。

psot请求不会被缓存

post请求不会保留在浏览器历史记录中

post请求不能被收藏为书签

post请求对数据长度没有要求

下面还有一些其他的HTTP请求方法

HEAD  与get相同,但只返回http报头,不返回文档主体。

PUT  上传指定的URI表示

DELETE 删除指定资源

OPTIONS 返回服务器支持的HTTP方法

CONNECT 把请求连接转换到透明的TCP/IP通道。

==========================================================================================

上面是http的post和get请求的概念,下面是本人的实例。本人是做java开发的。涉及到java开发的各种请求网络的资源,同时牵扯到jdk版本的不同对于http请求方法也不同。同时又涉及tomcat和weblogic的不同,请求网络也不同。中间跌跌撞撞走了很多的弯路。走弯路不可怕,可怕的是不能一直走弯路。下面我会一一罗列jdk版本的不同,不同java实例代码。

jdk1.8+tomcat

    /**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl  请求地址
	 * @param requestMethod  请求方式(GET、POST)
	 * @param outputStr  提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 * @throws IOException 
	 */
	public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)   {
		HttpsURLConnection httpUrlConn = null;
		OutputStream outputStream = null ;
		InputStream inputStream = null;
		
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new MyX509TrustManager() };
		try{
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL url = new URL(requestUrl);
		 httpUrlConn = (HttpsURLConnection) url.openConnection();
		httpUrlConn.setSSLSocketFactory(ssf);
		httpUrlConn.setDoOutput(true);
		httpUrlConn.setDoInput(true);
		httpUrlConn.setUseCaches(false);
		// 设置请求方式(GET/POST)
		httpUrlConn.setRequestMethod(requestMethod);

			httpUrlConn.connect();

		// 当有数据需要提交时
		if (null != outputStr) {
			 outputStream = httpUrlConn.getOutputStream();
			// 注意编码格式,防止中文乱码
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}

		// 将返回的输入流转换成字符串
		 inputStream = httpUrlConn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

		String str = null;
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		bufferedReader.close();
		inputStreamReader.close();
		jsonObject = JSONObject.fromObject(buffer.toString());
		}catch(Exception e){
			logger.error("网络请求错误  class-httpRequest-error={}",e);
			e.printStackTrace();
		}finally{
			// 释放资源
			try {
				if(inputStream != null){
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			inputStream = null;
			if (httpUrlConn != null ){
				httpUrlConn.disconnect();
			}
		}
		return jsonObject;
	}

 创建SSLContext对象,并使用我们指定的信任管理器初始化

import java.security.cert.CertificateException;  
import java.security.cert.X509Certificate;  
  
import javax.net.ssl.X509TrustManager; 

public class MyX509TrustManager implements X509TrustManager {  
  
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
    }  
  
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
    }  
  
    public X509Certificate[] getAcceptedIssuers() {  
        return null;  
    }  
} 

jdk1.6+weblogic

post请求

 public static String HttpsRequestByWeblogic(String url,String jsonMess){
		String returnMess = "";
		CloseableHttpClient httpClient = null;
		if(jsonMess!=null){
			HttpPost httpPost;
			try {
				httpClient = (CloseableHttpClient) wrapClient();
				httpPost = new HttpPost(url);
				StringEntity entity = new StringEntity(jsonMess);
				httpPost.setEntity(entity);
				CloseableHttpResponse response = httpClient.execute(httpPost);
				HttpEntity resEntity = response.getEntity();
				returnMess = EntityUtils.toString(resEntity, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			HttpGet httpGet = null;
			try {
				httpClient = (CloseableHttpClient) wrapClient();
				httpGet = new HttpGet(url);
				CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
				HttpEntity httpEntity = httpResponse.getEntity();
				returnMess = EntityUtils.toString(httpEntity, "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		 return returnMess;
	 }

HTTPS 获取信任证书

public static HttpClient wrapClient() {

		try {

			SSLContext context = SSLContext.getInstance("SSL");

			X509TrustManager manager = new X509TrustManager() {

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub

				}

				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					// TODO Auto-generated method stub

				}
			};

			context.init(null, new TrustManager[] { manager }, null);

			SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context,
					NoopHostnameVerifier.INSTANCE);

			CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(context).build();
			return httpClient;
		} catch (Exception e) {
			return HttpClients.createDefault();
		}
	}

目前就这么多,希望能帮助你!如果觉得可以点个赞。

猜你喜欢

转载自blog.csdn.net/qq_38366111/article/details/81501443