HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
在开发中经常遇到和第三方公司接口对接,需要拿到对方提供的数据或者是给对方提供,下面给大家提供一个自己写的demo,本地测试有效,利用post请求传参访问 ,希望可以帮到你学习
package test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class InterfaceRequest {
public static void main(String[] args) {
String url = "https://www.jianliyisheng.com/api/site/getprovincedata";
HttpClient client = HttpClients.createDefault();
//默认post请求
HttpPost post = new HttpPost(url);
//拼接多参数
JSONObject json = new JSONObject();
json.put("uid", "79");
json.put("key", "d86e33fb43036df9f9c29ff8085ac653");
json.put("timestamp", "1562296283");
json.put("typekey", "wshh");
try {
post.addHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8")));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
System.err.println("状态:" + httpResponse.getStatusLine());
System.err.println("参数:" + EntityUtils.toString(entity));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}