HttpClient执行post请求


public class Httpclient_post {
private ResourceBundle bundle;
private String url;
private BasicCookieStore store;
 //方法执行前先读取resource文件夹下的application文件中的url参数

@BeforeMethod
public void get_url(){
bundle =ResourceBundle.getBundle("application", Locale.CHINA);
url = bundle.getString("test.url");
}
//获取cookie
@Test
public void testGetCookies_read() throws IOException {
String result;
String uri = bundle.getString("getCookies.url");
String testUri = this.url+uri;
this.store = new BasicCookieStore();
//获取响应
HttpGet get = new HttpGet(testUri);
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
HttpResponse response = client.execute(get);
result = EntityUtils.toString(response.getEntity(),"utf-8");
System.out.println(result);
//获取cookie
List<Cookie> cookies = store.getCookies();
for (Cookie cookie :cookies
) {
String name = cookie.getName();
String value = cookie.getValue();
System.out.println("cookie: key= "+name +",name="+value);
}
}

//获取cookie并发送请求
//依赖读取cookie的方法,cookie存放在store中

@Test(dependsOnMethods ={"testGetCookies_read"} )
public void getPost_cookie() throws IOException {
//获取请求url
String ur = url+bundle.getString("test.get.with.cookies.post");
System.out.println(ur);
HttpPost post = new HttpPost(ur);
CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build();
//设置请求头信息
post.setHeader("content-type","application/json");
//设置jsong格式的请求参数
JSONObject param = new JSONObject();
param.put("name","hu");
param.put("age","18");
//将请求参数添加到方法中
StringEntity entity = new StringEntity(param.toString());
post.setEntity(entity);
//存贮响应结果
String result;
CloseableHttpResponse response = client.execute(post);
//获取响应结果
result = EntityUtils.toString(response.getEntity());
System.out.println(result);
//处理结果,判断结果是否符合预期
//将响应的结果字符串转换成json
JSONObject restjson = new JSONObject(result);
String success = (String) restjson.get("gg");
String status = (String) restjson.get("status");
Assert.assertEquals("success",success);
Assert.assertEquals("1",status);
}
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM