HttpClient发送Post与Get请求

发送Post请求

public class PostDemo {


    public static void main(String[] args) throws IOException {
        //请求URL
        String url = "";

        //请求方式
        HttpPost post = new HttpPost(url);

        //请求参数
        String  param1 = "";
        String  param2 = "";
        List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
        parameters.add(new BasicNameValuePair("param1",param1));
        parameters.add(new BasicNameValuePair("param2",param2));
        //请求头
        post.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
        //发起请求
        HttpClient client = HttpClients.createDefault();
        HttpResponse httpResponse = client.execute(post);
        //返回结果
        /**响应报文:
         状态行=http version + status code + reason phrase (HTTP/1.1 200 ok)
         响应头(k-v格式):服务器类型+日期+长度+内容类型+内容长度等等。
         相应正文:服务器返回的html页面或者json数据**/
        //状态行,状态码
        int code = httpResponse.getStatusLine().getStatusCode();
        System.out.println(code);
        HttpEntity entity = httpResponse.getEntity();
        System.out.println(entity);
        //响应正文
        String result = EntityUtils.toString(httpResponse.getEntity());
        System.out.println(result);

    }

 

发送Get请求

public class GetDemo {


    public static void main(String[] args) throws IOException {
        //请求URL
        String url = "";

        //请求参数
        String  param1 = "";
        String  param2 = "";
        url = url+"?"+param1+"="+param1+"&"+param2+"="+param2;
        //请求方式
        HttpGet get = new HttpGet(url);
        //发起请求
        HttpClient client = HttpClients.createDefault();
        HttpResponse httpResponse = client.execute(get);
        //返回结果
        //状态行,状态码
        int code = httpResponse.getStatusLine().getStatusCode();
        System.out.println(code);
        //响应正文
        String result = EntityUtils.toString(httpResponse.getEntity());
        System.out.println(result);

    }

 

上一篇:HPPT请求与响应处理


下一篇:post与get,关于终端