Java學習心得之 HttpClient的GET和POST請求,學習心得httpclient

來源:互聯網
上載者:User

Java學習心得之 HttpClient的GET和POST請求,學習心得httpclient
作者:楓雪庭出處:http://www.cnblogs.com/FengXueTing-px/歡迎轉載

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;    

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.