1.Get方法
import com.alibaba.fastjson.JSONObject;
import edu.zhku.fire_ant_project.config.WxConstant;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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;
public class HttpCallOtherInterfaceUtils {
public static void main(String args[]) {
HttpClient client = HttpClients.createDefault();
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WxConstant.appid +"&secret="+WxConstant.secret;
HttpGet httpGet=new HttpGet(url);
JSONObject jsonObject = null;
try {
HttpResponse res = client.execute(httpGet);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
System.out.println(jsonObject);
}
} catch (Exception e) {
System.out.println("服务间接口调用出错!");
e.printStackTrace();
}
}
}
2. post方法
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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;
public class HttpCallOtherInterfaceUtils {
public static String callOtherInterface(JSONObject jsonParam, String port, String postUrl) {
HttpClient client = HttpClients.createDefault();
String url = "http://localhost:" + port + postUrl;
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(jsonParam.toString(), "UTF-8");
s.setContentType("application/json");
post.setEntity(s);
post.addHeader("content-type", "application/json;charset=UTF-8");
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
}
} catch (Exception e) {
System.out.println("服务间接口调用出错!");
e.printStackTrace();
}
return jsonObject.toString();
}
}