用http和https请求进行访问数据


首先,我是用tomcat作为服务器,默认https不开启,需要自行设置,参考http://blog.csdn.net/w_liujun/article/details/41541267

和参考的文章一样,使用8443端口,需要在tomcat-conf-server.xml进行配置。

<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol" SSLEnabled="true"
           enableLookups="false"
           acceptCount="100" disableUploadTimeout="true"
           maxThreads="150" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           keystoreFile="C:/Program Files/Java/keystore-file"
           keystorePass="123456" />

放在如下注释的前面(在这里被坑了,导致一直无法访问到8443端口)

    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->
配置完后需要重启tomcat服务器。


然后我们是通过编写servlet处理请求,请求数据格式是json,返回数据格式也是json,并且打印返回的数据。


首先在web.xml中配置servlet,java文件是controller包下的JSONServlet类,访问路径是/servlet/JSONServlet.

<servlet>
    <servlet-name>JSONServlet</servlet-name>
    <servlet-class>controller.JSONServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>JSONServlet</servlet-name>
    <url-pattern>/servlet/JSONServlet</url-pattern>
  </servlet-mapping>


然后是JSONServlet类

因为要应用json,所以要导入相应的包(json-lib等等)链接:http://download.csdn.net/detail/tyfengyu/4478154

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



public class JSONServlet extends HttpServlet{

	protected void doGet(HttpServletRequest request,HttpServletResponse response){
		doPost(request, response);
	}
	
	protected void doPost(HttpServletRequest request,HttpServletResponse response){
		
		BufferedReader br;
		StringBuilder sb = new StringBuilder();
		// 获取请求
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			 br = new BufferedReader(new InputStreamReader(request.getInputStream()));
	        String line = null;
	        while((line = br.readLine())!=null){
	            sb.append(line);
	        }
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}

        // 将资料解码
        String reqBody = sb.toString();
        System.out.println("reqBody:"+reqBody);
		JSONObject JSONVersion =  JSONObject.fromObject(reqBody);
		
		System.out.println(JSONVersion.toString());
		
		// 获取版本号进行比较
		String UserVersion = JSONVersion.getString("filename");
		
//		System.out.println("UserVersion" + UserVersion);
        
		//查询数据库返回真实信息
		
		// 返回JSON文件
		String result = JSONString();
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
		
			e.printStackTrace();
		}
	}
	
	public String JSONString()
	{
		// json对象
		JSONObject gujian = new JSONObject();
		
		
		
		gujian.put("version", "2.27");
		
		JSONObject ALL =new JSONObject();
		ALL.put("gujian", gujian);
		
 		
		// String result = "{"+jsonArray.toString()+"}";
		String result = ALL.toString();
		return result;
	}
}

http请求:(httpRequest类)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;

public class HttpRequest {
	 public static final String ADD_URL = "http://localhost:8080/test2/servlet/JSONServlet";  
	 //   public static final String ADD_URL = "http://192.168.4.97:35357/v2.0/tokens";  
	    public static void appadd() throws IOException {  
	        HttpURLConnection connection=null;  
	        try {  
	             //创建连接  
	             URL url = new URL(ADD_URL);  
	             connection = (HttpURLConnection) url.openConnection();  
	               
	  
	             //设置http连接属性  
	               
	             connection.setDoOutput(true);  
	             connection.setDoInput(true);  
	             connection.setRequestMethod("POST"); // 可以根据需要 提交 GET、POST、DELETE、INPUT等http提供的功能  
	             connection.setUseCaches(false);  
	             connection.setInstanceFollowRedirects(true);  
	               
	             //设置http头 消息  
	             connection.setRequestProperty("Content-Type","application/json");  //设定 请求格式 json,也可以设定xml格式的  
	             //connection.setRequestProperty("Content-Type", "text/xml");   //设定 请求格式 xml,  
	             connection.setRequestProperty("Accept","application/json");//设定响应的信息的格式为 json,也可以设定xml格式的  
//	             connection.setRequestProperty("X-Auth-Token","xx");  //特定http服务器需要的信息,根据服务器所需要求添加  
	             connection.connect();  
	   
	             //添加 请求内容  
	               
	            JSONObject user = new JSONObject();    
	            user.put("filename", "2.26");  
	             OutputStream out = connection.getOutputStream();                          
	             out.write(user.toString().getBytes());  
	             out.flush();  
	             out.close();  
	   
	             //	 读取响应  
	             BufferedReader reader = new BufferedReader(new InputStreamReader(  
	                     connection.getInputStream()));  
	             String lines;  
	             StringBuffer sb = new StringBuffer("");  
	             while ((lines = reader.readLine()) != null) {  
	                 lines = new String(lines.getBytes(), "utf-8");  
	                 sb.append(lines);  
	             }  
	             System.out.println(sb);  
	             reader.close();  
	              断开连接  
	             connection.disconnect();  
	         } catch (MalformedURLException e) {  
	             // TODO Auto-generated catch block  
	             e.printStackTrace();  
	         } catch (UnsupportedEncodingException e) {  
	             // TODO Auto-generated catch block  
	             e.printStackTrace();  
	         } catch (IOException e) {  
	             // TODO Auto-generated catch block  
	             e.printStackTrace();  
	         }  
	   
	    }  
	  
	   
	    public static void main(String[] args) throws IOException {  
	         appadd();  
	     }  
    
}

https请求,本地测试忽略证书进行请求 (httpsRequest类)
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import net.sf.json.JSONObject;

public class HttpsRequest {

	// 表示服务器端的url
	private static String PATH = "https://localhost:8443/test2/servlet/JSONServlet";
	private static URL url;

	static HostnameVerifier hv = new HostnameVerifier() {  
        public boolean verify(String urlHostName, SSLSession session) {  
            System.out.println("Warning: URL Host: " + urlHostName + " vs. "  
                               + session.getPeerHost());  
            return true;  
        }
    };  
	public HttpsRequest() {
		// TODO Auto-generated constructor stub
	}

	 private static void trustAllHttpsCertificates() throws Exception {  
	        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];  
	        javax.net.ssl.TrustManager tm = new miTM();  
	        trustAllCerts[0] = tm;  
	        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext  
	                .getInstance("SSL");  
	        sc.init(null, trustAllCerts, null);  
	        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc  
	                .getSocketFactory());  
	    }  
	 
	 static class miTM implements javax.net.ssl.TrustManager,  
     javax.net.ssl.X509TrustManager {  
	 public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
	     return null;  
	 }  
	
	 public boolean isServerTrusted(  
	         java.security.cert.X509Certificate[] certs) {  
	     return true;  
	 }  
	
	 public boolean isClientTrusted(  
	         java.security.cert.X509Certificate[] certs) {  
	     return true;  
	 }  
	
	 public void checkServerTrusted(  
	         java.security.cert.X509Certificate[] certs, String authType)  
	         throws java.security.cert.CertificateException {  
	     return;  
	 }  
	
	 public void checkClientTrusted(  
	         java.security.cert.X509Certificate[] certs, String authType)  
	         throws java.security.cert.CertificateException {  
	     return;  
	 }  
	}  
	static {
		try {
			url = new URL(PATH);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * params 填写的URL的参数 encode 字节编码
	 */
	public static void sendPostMessage(String encode) {

		// 忽略证书
		try {
			trustAllHttpsCertificates();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	    HttpsURLConnection.setDefaultHostnameVerifier(hv); 
		StringBuffer stringBuffer = new StringBuffer();
		
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setConnectTimeout(3000);
			httpURLConnection.setDoInput(true);// 从服务器获取数据
			httpURLConnection.setDoOutput(true);// 向服务器写入数据

//			 获得上传信息的字节大小及长度
		  JSONObject user = new JSONObject();    
            user.put("filename", "2.26");  
			// 设置请求体的类型
			httpURLConnection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			httpURLConnection.setRequestProperty("Content-Lenth",
					String.valueOf(user.toString().length()));

			// 获得输出流,向服务器输出数据
			OutputStream outputStream = (OutputStream) httpURLConnection
					.getOutputStream();
			outputStream.write(user.toString().getBytes());

			// 获得服务器响应的结果和状态码
			int responseCode = httpURLConnection.getResponseCode();
			if (responseCode == 200) {

				// 获得输入流,从服务器端获得数据
				InputStream inputStream = (InputStream) httpURLConnection
						.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(  
						inputStream));  
	            String lines;  
	            StringBuffer sb = new StringBuffer("");  
	            while ((lines = reader.readLine()) != null) {  
	                lines = new String(lines.getBytes(), "utf-8");  
	                sb.append(lines);  
	            }  
	            System.out.println(sb);  
	            reader.close();  
				

			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		sendPostMessage("utf-8");
	}

}

启动tomcat,分别运行httpRequest类和httpsRequest类进行测试。

控制台打印出 {"gujian":{"version":"2.27"}} 代表运行成功。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值