package com.lyl.interfaces;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
public class Demo {
//日志
private Logger logger=Logger.getLogger(Demo.class);
@Test(enabled=false)
public void testLoginPost() {
//准备url
String url = "http://******/api/member/login";
//选择请求方式
HttpPost httppost = new HttpPost(url);
//准备参数
List<BasicNameValuePair> para=new ArrayList<BasicNameValuePair>();
BasicNameValuePair mobliePhone= new BasicNameValuePair("mobilephone","**********");
BasicNameValuePair pwd=new BasicNameValuePair("password", "e10adc3949ba59abbe56e057f20f883e");
BasicNameValuePair type=new BasicNameValuePair("type", "1");
para.add(mobliePhone);
para.add(pwd);
para.add(type);
try {//把参数封装到请求体里面
httppost.setEntity(new UrlEncodedFormEntity(para,"UTF-8"));
//准备客户端
HttpClient httpclient =HttpClients.createDefault();
//发送请求,接受响应信息
HttpResponse respones=httpclient.execute(httppost);
//取出接口响应数据,并转成字符串
String result= EntityUtils.toString(respones.getEntity());
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("post请求出问题啦");
}
}
@Test
public void testLoginGet(){
//准备url
String url = "http://*******/api/member/login";
//选择请求方式
HttpGet httpget = new HttpGet(url);
//准备参数
List<BasicNameValuePair> para=new ArrayList<BasicNameValuePair>();
BasicNameValuePair mobliePhone= new BasicNameValuePair("mobilephone","*****");
BasicNameValuePair pwd=new BasicNameValuePair("password", "e10adc3949ba59abbe56e057f20f883e");
BasicNameValuePair type=new BasicNameValuePair("type", "1");
para.add(mobliePhone);
para.add(pwd);
para.add(type);
String paramers=URLEncodedUtils.format(para, "UTF-8");
//将参数拼接在url上面
url+=("?"+paramers);
try {
httpget.setURI(new URI(url));
//准备客户端
HttpClient httpclient=HttpClients.createDefault();
//执行
HttpResponse response=httpclient.execute(httpget);
String result=EntityUtils.toString(response.getEntity());
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("get请求出问题啦");
}
}
}
用java语言编写一个简单的接口请求,get和post
最新推荐文章于 2025-03-07 00:15:00 发布