7.15Java之调用API接口传表单获取返回信息
2021-07-23 12:55
标签:post请求 upload str 新建 eth http mod mode use 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既是我们的表单*/
ListNameValuePair> nameValuePairs = new ArrayListNameValuePair>();
?
//在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.
上一篇:c++ 结构体容器(vector)类型初始化及结构体vector指针传递
下一篇:js中的charAt()与charCodeAt(),fromCharCode(),fromCodePoint()