HttpURLConnection 使用 & MissingServletRequestParameterException异常处理

http请求处理工具类

HttpURLConnection 概述

public abstract class HttpURLConnection extends URLConnection
A URLConnection with support for HTTP-specific features. See the spec for details.

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP 
server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream 
of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on 
any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.

The HTTP protocol handler has a few settings that can be accessed through System Properties. This covers Proxy settings as well as various other settings.
  • 支持 HTTP 特定功能的 URL 连接。有关详细信息,请参阅规格。
  • 每个 HttpURLConnection 实例都用于发出单个请求,但与 HTTP 服务器的基础网络连接可能由其他实例透明地共享。在请求后在 HttpURLConnection 的输入流或输出流上调用 close() 方法可能会释放与此实例关联的网络资源,但对任何共享持久连接没有任何影响。如果持久连接在当时处于空闲状态,则调用断开连接() 方法可能会关闭基础套接字。
  • HTTP 协议处理程序有几个可以通过系统属性访问的设置。这包括代理设置以及各种其他设置。

HttpURLConnection 使用案例

GET 请求

public static void main(String[] args) throws IOException {
    
    
     
     // request url
     String URL = "https://xxx.xxxxxxxx.com/xxxx/xxxxx";

     // test get
     initGetParams();
     String getRet = testGet(URL);
     System.out.println(getRet);
 }

/**
  * get 请求处理方法
  * @param path
  * @return
  * @throws IOException
  */
 private static String testGet(String path) throws IOException {
    
    

     BufferedReader in = null;
     StringBuilder sb = new StringBuilder();
     try {
    
    

         // get
         String mPath = path + "?";
         for (String key : getParams.keySet()) {
    
    
             mPath += key + "=" + getParams.get(key) + "&";
         }
         URL url = new URL(mPath);
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();

         // set connection params
         conn.setRequestMethod("GET");
         conn.setDoOutput(false);
         conn.setDoInput(true);
         conn.setConnectTimeout(10000);
         conn.setReadTimeout(10000);
         conn.setRequestProperty("accept", "*/*");
         conn.setRequestProperty("connection", "Keep-Alive");
         conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
         conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
         conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
         conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
         conn.setRequestProperty("Cookie", "xxx-xxxx-xxxxx-xxxx");
         conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

         // connect
         conn.connect();

         // reader
         in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

         String line;
         while ((line = in.readLine()) != null) {
    
    
             sb.append(line);
         }
     } catch (Exception e) {
    
    
         System.err.println("调用异常:" + e);
     } finally {
    
    

         // close stream
         if (in != null) {
    
    
             in.close();
         }
     }
     return sb.toString();
 }

 /**
  * 初始化 get 请求参数
  */
 private static void initGetParams() {
    
    

     getParams.put("param1", "value1");
     getParams.put("param2", "value2");
     getParams.put("param3", "value3");
     getParams.put("param4", "value4");
 }

POST请求

public static void main(String[] args) throws IOException {
    
    
     
     // request url
     String URL = "https://xxx.xxxxxxxx.com/xxxx/xxxxx";

     // test post
     initPostParams();
     String postRet = testPost(URL, postParams);
     System.out.println(postRet);
 }

/**
  * post 请求处理方法
  * @param requestUrl
  * @param params
  * @return
  * @throws IOException
  */
 public static String testPost(String requestUrl, String params) throws IOException {
    
    

     OutputStreamWriter out = null;
     BufferedReader in = null;
     StringBuilder sb = new StringBuilder();
     try {
    
    
         URL url = new URL(requestUrl);
         HttpURLConnection conn = (HttpURLConnection) url
                 .openConnection();

         // set connection params
         conn.setDoOutput(true);
         conn.setDoInput(true);
         conn.setUseCaches(false);
         conn.setInstanceFollowRedirects(true);
         conn.setRequestMethod("POST");
         conn.setRequestProperty("Accept", "*/*");
         conn.setRequestProperty("connection", "Keep-Alive");
         conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
         // conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
         // conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");
         conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
         conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
         conn.setRequestProperty("Cookie", "xxx-xxxx-xxxxx-xxxx");

         // connect
         conn.connect();
         out = new OutputStreamWriter(
                 conn.getOutputStream(), "UTF-8");
         out.append(params);
         out.flush();
         out.close();
         if (conn != null) {
    
    

             // reader
             in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
             String line = null;
             while ((line = in.readLine()) != null) {
    
    
                 sb.append(line);
                 sb.append("\r\n");
             }
         }

         // connection disconnect
         conn.disconnect();
     } catch (IOException e) {
    
    
         System.err.println("调用异常:" + e);
     } finally {
    
    

         // close stream
         if (out != null) {
    
    
             out.close();
         }
         if (in != null) {
    
    
             in.close();
         }
     }
     return sb.toString();
 }

/**
  * 初始化 post 请求参数
  */
 private static void initPostParams() {
    
    
     StringBuffer sb=new StringBuffer();
     sb.append("param1=").append("value1&").append("param2=").append("value2&").append("param3=").append("value3&").append("param4=").append("value4");
     postParams =  sb.toString();
 }

总结

MissingServletRequestParameterException

测试HttpURLConnection如上所述,期间POST请求出现问题

{
    
    
	"@type": "org.springframework.web.bind.MissingServletRequestParameterException",
	"cause": null,
	"localizedMessage": "Required String parameter 'order_type' is not present",
	"message": "Required String parameter 'order_type' is not present",
	"parameterName": "order_type",
	"parameterType": "String",
	"rootCause": null,
	"stackTrace": ...
}

经检查参数个数,参数名称均无误,怀疑是请求头、响应头类型解析不一致解决方案如下:

// conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// conn.setRequestProperty("Accept", "application/json, text/javascript, */*; q=0.01");

猜你喜欢

转载自blog.csdn.net/shang_xs/article/details/107000439