7.15Java之呼叫API介面傳表單獲取返回資訊
阿新 • • 發佈:2021-07-15
例項
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