Http請求接口的模板

  1. 使用Apache的HttpClient
    @Controller
    public class HttpDemo {

    //接口地址
    private String url = “http://ws.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline”;

    //GET請求

  @RequestMapping("getInfo")
   @ResponseBody
   public String getInfo(){
       HttpClient httpClient = HttpClientBuilder.create().build();
       HttpGet httpGet = new HttpGet(url + "?qqCode=222222222");
       try {
           HttpResponse response = httpClient.execute(httpGet);
           HttpEntity entity = response.getEntity();
           return EntityUtils.toString(entity, "utf-8");
       } catch (IOException e) {
           e.printStackTrace();
       }
       return "";
   }

//POST請求

   @RequestMapping("postInfo")
   @ResponseBody
   public String postInfo(){
       HttpClient httpClient = HttpClientBuilder.create().build();
       List<NameValuePair> params = new ArrayList<NameValuePair>();
       params.add(new BasicNameValuePair("qqCode","222222222"));
       UrlEncodedFormEntity entity1 = null;
       try {
           entity1 = new UrlEncodedFormEntity(params, "utf-8");
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       }
       HttpPost httpPost = new HttpPost(url);
       httpPost.setEntity(entity1);
       httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
       HttpResponse response = null;
       try {
           response = httpClient.execute(httpPost);
       } catch (IOException e) {
           e.printStackTrace();
       }
       HttpEntity entity2 = response.getEntity();
       String ret = "";
       try {
           ret = EntityUtils.toString(entity2, "utf-8");
       } catch (IOException e) {
           e.printStackTrace();
       }
       return ret;
   }

}

  1. 使用JDK自帶的HttpUrlConnection
    @Controller
    public class HttpDemo {
    //接口地址
    private String addr = “http://ws.webxml.com.cn/webservices/qqOnlineWebService.asmx/qqCheckOnline”;

    //GET請求

    @RequestMapping("getInfo")
    @ResponseBody
    public String getInfo() {
        URL url = null;
        try {
            url = new URL(addr + "?qqCode=347635191");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.setDoOutput(true);
        connection.setDoInput(true);
        try {
            connection.setRequestMethod("GET");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        try {
            connection.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String line;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.getProperty("line.separator"));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        try {
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
        return sb.toString();
    }
    

    //POST請求

    @RequestMapping("postInfo")
    @ResponseBody
    public String postInfo(){
        Map<String,String> param = new HashMap<String,String>();
        param.put("qqCode","347635191");
        URL url = null;
        try {
            url = new URL(addr);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.setDoOutput(true);
        connection.setDoInput(true);
        try {
            connection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            e.printStackTrace();
        }
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        try {
            connection.connect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataOutputStream dataout = null;
        try {
            dataout = new DataOutputStream(connection.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        String paramStr =builderUrlParams(param);
        try {
              dataout.writeBytes(paramStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        BufferedReader bf = null;
        try {
            bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String line;
        StringBuilder sb = new StringBuilder();
        try {
            while ((line = bf.readLine()) != null) {
                sb.append(line).append(System.getProperty("line.separator"));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        try {
            bf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        connection.disconnect();
        return sb.toString();
        }
    

    //構造HttpURLConnection進行Post請求所需要的參數

 public static String builderUrlParams(Map<String, String> params){
     Set<String> keySet = params.keySet();
     List<String> keyList = new ArrayList<String>(keySet);
     Collections.sort(keyList);
     StringBuilder sb = new StringBuilder();
     for (String key : keyList) {
         String value = params.get(key);
         if (StringUtils.isEmpty(value)) {
             continue;
         }
         sb.append(key);
         sb.append("=");
         try {
             sb.append(URLEncoder.encode(params.get(key),"UTF-8"));
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         }
         sb.append("&");
     }
     sb.deleteCharAt(sb.length() - 1);
     return sb.toString();
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章