Java学习心得之 HttpClient的GET和POST请求

Posted 枫雪庭

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java学习心得之 HttpClient的GET和POST请求相关的知识,希望对你有一定的参考价值。

Java学习心得之 HttpClient的GET和POST请求

1. 前言
2. GET请求
3. POST请求 

 

一、前言

本篇博文记录了HttpClient的GET和POST请求

本文内容基于以下文章:

http://huangqiqing123.iteye.com/blog/2054436                       (HttpClient之 addHeader与setHeader)
http://zywang.iteye.com/blog/916834                            (使用Apache HttpClient访问JSP发送GET和POST请求)
http://www.linuxidc.com/Linux/2012-02/55502p3.htm                  (HttpClient 4.0的使用详解)

 

二、GET请求

GET请求的实例如下:

    //httpClient
    HttpClient httpClient = new DefaultHttpClient();

    // get method
    HttpGet httpGet = new HttpGet("https://api.microsofthealth.net/v1/me/Summaries/Daily");
    
    // set header
    String Au="Bearer "+access_token;
    httpGet.setHeader("Authorization",Au);  
  
    //response
    HttpResponse response = null;  
    try{
        response = httpClient.execute(httpGet);
    }catch (Exception e) {} 

    //get response into String
    String temp="";
    try{
        HttpEntity entity = response.getEntity();
        temp=EntityUtils.toString(entity,"UTF-8");
    }catch (Exception e) {} 
    
    return temp;

 

三、POST请求:

GET请求的实例如下:

    //httpClient
    HttpClient httpClient = new DefaultHttpClient();

    // get method
    HttpPost httpPost = new HttpPost("https://login.live.com/oauth20_token.srf");    
  
    // set header
    httpPost.setHeader("Content-Type","application/x-www-form-urlencoded"); 

    //set params
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("client_id",client_id));
    params.add(new BasicNameValuePair("redirect_uri",redirect_uri));
    params.add(new BasicNameValuePair("client_secret",client_secret));
    params.add(new BasicNameValuePair("code",code));
    params.add(new BasicNameValuePair("grant_type","authorization_code"));
    try{
        httpPost.setEntity(new UrlEncodedFormEntity(params));
    }catch (Exception e) {} 

    //response
    HttpResponse response = null;  
    try{
        response = httpClient.execute(httpPost);
    }catch (Exception e) {}
    
    //get response into String
    String temp="";
    try{
        HttpEntity entity = response.getEntity();
        temp=EntityUtils.toString(entity,"UTF-8");
    }catch (Exception e) {}
    
    return temp;    

 

以上是关于Java学习心得之 HttpClient的GET和POST请求的主要内容,如果未能解决你的问题,请参考以下文章

关于HttpClient的学习心得,请求参数中文乱码问题

Java爬虫技术之HttpClient学习笔记

Java接口自动化测试之HTTPClient学习

Java学习心得之 Linux下搭建JavaWeb环境

Http (java)的post和get方式

HttpClient的get和post请求处理