• 7.15Java之调用API接口传表单获取返回信息


    7.15Java之调用API接口传表单获取返回信息

    实例

    package GoogleTranslateAPI;

    import com.alibaba.fastjson.JSON;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;

    /**
    * 使用HttpClient类测试翻译接口
    * @since JDK 1.8
    * @date 2021/07/15
    * @author Lucifer
    */
    public class TranslateAPITest {
       //定义接口API地址
       private static final String Url = "";
       /**
        *用HttpClient类下的方法创建POST请求demo
        */
       public static void doPostForm(String url) throws IOException {
           //使用HttpClient创建客户端
           CloseableHttpClient httpClient = HttpClientBuilder.create().build();
           //创建HttpPost类引用
           HttpPost httpPost = new HttpPost(url);
           /*这个httpPost既是我们的表单*/
           List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

           //在List引用里面添加参数
           nameValuePairs.add(new BasicNameValuePair("trans_data","[{\"custom_index\":1," +
                   "\"lang_tgt\":\"zh\"," +
                   "\"trans_text\":\"HelloWorld\"}]"));
    //       UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs);
    //       httpPost.setEntity(urlEncodedFormEntity);
    //       httpClient.execute(httpPost);

           //将参数放在请求体里面传过去的
           String jsonString = JSON.toJSONString(nameValuePairs);
           StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");

           //将entity放入post请求体中
           httpPost.setEntity(stringEntity);
           httpPost.setHeader("Content-Type", "multipart/form-data;charset=utf8");

           //响应模型
           CloseableHttpResponse response = null;
           try {
               //由客户端执行发送Post请求
               response = httpClient.execute(httpPost);
               //从响应模型中获得响应实体
               HttpEntity responseEntity = response.getEntity();
               //打印响应状态
               System.out.println("响应状态为:" + responseEntity.getContentLength());
               //判断
               if (responseEntity!=null){
                   System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                   System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
              }
          }catch (Exception e){
               System.out.println(e.getMessage());
               e.printStackTrace();
          }finally {
               //关闭资源
               try {

                   if (httpClient != null) {
                       httpClient.close();
                  }
                   if (response != null) {
                       response.close();
                      }
                  }catch (Exception e){
                   System.out.println(e.getMessage());
                   e.printStackTrace();
              }
          }
      }

       public static void main(String[] args) throws IOException {
           doPostForm(Url);
      }
    }

    上面是使用了阿里封装好的类,下面根据实际的API请求过程写一个具体的请求方法

    package OMSAPI;

    import org.testng.annotations.Test;

    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;

    /**
    * 测试从OMS系统找到的API
    * @since JDK 1.8
    * @date 2021/07/15
    * @author Lucifer
    */
    public class OmsRealAPITest {
       /**
        * 首先分析该接口的几个关键数据
        * 1、接口地址:
        * 2、请求方式:POST
        * 3、接口请求头Content-Type:multipart/form-data--->分割线是----WebKitFormBoundaryvKoqOBacjc8vEEDj
        * 4、接口请求参数:id、name、type(图片)、lastModifiedDate、size、file(binary)
        */
       //定义换行符
       private static String newLine = "\r\n";
       //定义分隔符
       private static String BOUNDARY = "------WebKitFormBoundaryvKoqOBacjc8vEEDj";
       //定义接口地址
       private static String Url = "";
       //抓取到捕获的Cookie
       private static String Cookie = "thinkphp_show_page_trace=0|0;" +
               "_ati=9948700605832;" +
               "is_show_search=1;" +
               "users=-5PYsAYAeYYOh41Hi2idlIjgX8y1R6I1RsRb3LW-eDPstfTSSmzqgZOL43PQhRUY_K3yquAsSSIWsk40_rbAGwb-aymNgVPqbSa93YJtw_FTIWmAQj5q8_DRRduMPB1YdckZj8gPGBVo7c4uy3FkidzbcNXjf3aQ8jWPT5v_qyJQACNIcJaUFXfuOfO8sIr-hhz-AN-D2kOJGzFNP33KnwSI7Qb9zvnNGaMbCmS9JORQg6fZFvfdE8hJwY7DAzs17GvK1flYz3JtWXOZWcZ7ifZDbbo9MHT-xRO-QCstZEP2Xlp6ofwQcP6ivcbUAFSyCjsene7l4LuJYKTsoB56uPgoj6VjRCSGWl_jYLt7AO9AV79u7Y0DEd-jTXJfuH35cAdhVzU91EQdd5vEMv1k57b4F9D69pHw2ClujcTmKVkuEQPwof6Jjyh519GIfyiQjTRPXPpwVY0oXrNwTA0cRw;" +
               "think_var=zh-cn;" +
               "PHPSESSID=22d17805dc03a848a02df629ce90ce48;" +
               "thinkphp_show_page_trace=0|0";
       @Test
       public static HttpURLConnection uploadPicture(String picturepath) throws IOException {
           //使用URL类打开一个URL连接
           URL url = new URL(Url);
           //使用Http打开该连接
           HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
           //设置请求方式
           httpURLConnection.setRequestMethod("POST");
           //POST请求方式需要打开输入流和输出流
           httpURLConnection.setDoInput(true);
           httpURLConnection.setDoOutput(true);
           //设置无缓存
           httpURLConnection.setUseCaches(false);

           /*开始设置请求头参数--->根据接口的请求头信息设置*/
           try {
               //设置请求头参数
               httpURLConnection.setRequestProperty("Connection","keep-alive");
               httpURLConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
               httpURLConnection.setRequestProperty("Cookie",Cookie);
               httpURLConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36");

               /*制作表单*/
               //创建StringBuilder引用
               StringBuilder stringBuilder = new StringBuilder();
               //依据表单格式进行内容添加
               stringBuilder.append(BOUNDARY);
               stringBuilder.append(newLine);
               //加入Content-Description内容
               stringBuilder.append("Content-Disposition: form-data; name=\"id\";" + newLine + newLine +
                       "Content-Disposition: form-data; name=\"name\";" + newLine + newLine +
                       "Content-Disposition: form-data; name=\"type\";" + newLine + newLine +
                               "Content-Disposition: form-data; name=\"size\";" + newLine + newLine +
                       "Content-Disposition: form-data; name=\"file\"; filename=" + "Hello" + newLine + newLine +
                       BOUNDARY + "--"
                      );
               //参数头设置完成加两个换行
               stringBuilder.append(newLine);
               stringBuilder.append(newLine);

               //创建参数输出流
               OutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
               //将参数头的数据写入到输出流中
               outputStream.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));

               /*定义数据输入流,用于读取图片*/
               //新建文件对象引用
               File file = new File(picturepath);
               DataInputStream dataInputStream = new DataInputStream(
                       new FileInputStream(file)
              );
               //创建缓冲区
               byte[] bufferOut = new byte[1024*10];
               //首字符
               int bytes = 0;
               //每次读10KB写入输出流
               while ((bytes=dataInputStream.read(bufferOut))!=-1){
                   //写入输出流
                   outputStream.write(bufferOut);
              }
               //换行
               outputStream.write(newLine.getBytes(StandardCharsets.UTF_8)); //因为File的内容是二进制,所以需要转成比特流
               //关闭流
               dataInputStream.close();

               //定义最后数据分隔线,即加上BOUNDARY再加上--
               //换行+分割线+
               byte[] end_data = (newLine + BOUNDARY + "--").getBytes(StandardCharsets.UTF_8); //二进制,要转成比特流

               //写上结尾标识
               outputStream.write(end_data);
               //刷新缓冲区
               outputStream.flush();
               //关闭输出流
               outputStream.close();
          }catch (Exception e){
               throw new IOException();
          }finally {

          }

           return httpURLConnection;
      }

       /**
        * 定义BufferedReader输入流来读取URL响应
        */
       public static void getURLResponse() throws IOException {
           //使用API调用方法获得httpConnection对象引用
           BufferedReader bufferedReader = new BufferedReader(
                   new InputStreamReader(
                           uploadPicture("C:/Users/Administrator/Desktop/Test_Work/Test_Picture/staticPicture.jpg").getInputStream()
                  )
          );
           //读取URL响应信息
           String line;
           while ((line=bufferedReader.readLine())!=null){
               //按行写入
               System.out.println(line);
          }
      }

       public static void main(String[] args) throws IOException {
           getURLResponse();
      }
    }

     

    It's a lonely road!!!
  • 相关阅读:
    BASE64
    2020-2021-1 20201217《信息安全专业导论》第二周学习总结
    师生关系20201217
    2020-2021-1 20201217王菁<<信息安全专业导论>>第一周学习总结
    作业正文(快速浏览教材提出问题)
    自我介绍20201217王菁
    罗马数字转阿拉伯数字(20201225张晓平)
    20201225 张晓平《信息安全专业导论》第三周学习总结
    20201225 张晓平《信息安全专业导论》第二周学习总结
    我期待的师生关系
  • 原文地址:https://www.cnblogs.com/JunkingBoy/p/15017255.html
Copyright © 2020-2023  润新知