package postTest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class Test_01 {
public static void main(String[] args) throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
doGet();
doPost();
}
/**
* 在Get请求中,没有请求体,只有请求行和请求头<p>
* 响应包括:响应行——响应头——响应体三部分<p>
* ----其中HttpResponse包括相应行、响应头两部分<p>
* ----HttpEntity只包括响应体一部分<p>
* @throws ParseException
* @throws IOException
*/
public static void doGet() throws ParseException, IOException{
//创建一个客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求方式,并输入网址,请求行设置完毕,请求参数在?后面表示(表示请求参数)
HttpGet urlGet = new HttpGet("https://api.yonyoucloud.com/apis/dst/collegeInfoQuery/collegeInfoQuery?name=上海");
//设置请求头域
urlGet.setHeader("apicode", "d508e496d2804feb95b91eec4c926906");
//发送请求并获取响应结果,此时获取的时响应头
HttpResponse httpResponse = httpClient.execute(urlGet);
System.out.println(httpResponse);
//获取响应体
HttpEntity entity = httpResponse.getEntity();
System.out.println(entity);
//转换响应体
String responseStr = EntityUtils.toString(entity);
System.out.println(responseStr);
}
/**
* 在Post请求中,请求行,请求头,请求体都有<p>
* ----通过setHeader()或者addHeader()设置请求头<p>
* ----通过setEntity()的方式设置请求体<p>
* 响应包括:响应行——响应头——响应体三部分<p>
* ----其中HttpResponse包括相应行、响应头两部分<p>
* ----HttpEntity只包括响应体一部分<p>
* @throws ClientProtocolException
* @throws IOException
*/
public static void doPost() throws ClientProtocolException, IOException{
//创建一个客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置请求方式,并输入网址
HttpPost urlPost = new HttpPost("https://api.yonyoucloud.com/apis/pte/New_Issue_Bond_Information/New_Issue_Bond_Information");
//添加请求头
// urlPost.addHeader("apicode", "ed9415dba2bb4452b0ba0cf787e85c51");
urlPost.setHeader("apicode", "ed9415dba2bb4452b0ba0cf787e85c51");
urlPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//添加请求体
List<NameValuePair> parameters = new ArrayList<>();
parameters.add(new BasicNameValuePair("size", "1"));
HttpEntity requestEntity = new UrlEncodedFormEntity(parameters);
urlPost.setEntity(requestEntity);
//发送请求并获取响应结果,此时获取的时响应头
HttpResponse httpResponse = httpClient.execute(urlPost);
System.out.println(httpResponse);
//获取响应体
HttpEntity entity = httpResponse.getEntity();
System.out.println(entity);
//转换响应体
String responseStr = EntityUtils.toString(entity);
System.out.println(responseStr);
}
}