1. 程式人生 > 其它 >7.15Java之呼叫API介面傳表單獲取返回資訊

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!!!