利用httpclient發送GET/POST請求__java基礎

來源:互聯網
上載者:User

暫時唯寫post

import com.alibaba.fastjson.JSON;import org.apache.commons.lang.StringUtils;import org.apache.commons.lang.Validate;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import java.io.IOException;import java.util.HashMap;import java.util.Map;private Header[] headers = {new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +              "Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"),               new BasicHeader("Accept-Language", "zh-cn"),               new BasicHeader("Accept", " image/gif, image/x-xbitmap, image/jpeg, " +                      "image/pjpeg, application/x-silverlight, application/vnd.ms-excel, " +                      "application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*"),               new BasicHeader("Content-Type", "application/x-www-form-urlencoded"),               new BasicHeader("Accept-Encoding", "gzip, deflate")};  public static String post(String url, Map<String, String> params) throws IOException {        CloseableHttpClient httpClient = null;        String res = null;        try {            httpClient = HttpClients.createDefault();            HttpPost post = new HttpPost(url);            post.setHeaders(headers);            //如果有參數則設定參數            //StringEntity是最簡單的傳輸類型,UrlEncodedFormEntity繼承StringEntity,一般用於表單上傳,在StringEntity中,表單項的格式是key=value&key=value,            // 因為這裡只有一項表單,所以我用StringEntity            StringEntity stringEntity = new StringEntity("param="+JSON.toJSONString(params), ContentType.create("application/x-www-form-urlencoded", "UTF-8"));            //這個設定同上面的設定是不一樣的,上面的UTF-8是解析StringEntity中的傳入string的字元集,將其轉換為byte            stringEntity.setContentEncoding("utf-8");            post.setEntity(stringEntity);////            List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();//            paramList.add(new BasicNameValuePair("param", JSON.toJSONString(params)));//            post.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));            HttpResponse response = httpClient.execute(post);            int statusCode = response.getStatusLine().getStatusCode();            if (statusCode != HttpStatus.SC_OK) {                System.out.println("錯誤碼[" + statusCode + "]");            }            HttpEntity entity = response.getEntity();            if (entity != null) {                res = EntityUtils.toString(entity, "UTF-8");            }        } catch (Exception e) {            e.printStackTrace();            return null;        } finally {            if (null != httpClient) {                httpClient.close();            }        }        return res;    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.