天天看點

JAVA利用HttpClient和HttpURLConnection 進行POST和GET請求

小編在這裡講述在java中兩種常見調用接口的方式,同時提供多種類型選擇

    public static String postDownloadJson(String path,String post){

        URL url = null;

        try {

            url = new URL(path);

            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");// 送出模式

            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.setConnectTimeout(10000);//連接配接逾時 機關毫秒

            httpURLConnection.setReadTimeout(2000);//讀取逾時 機關毫秒

            // 發送POST請求必須設定如下兩行

            httpURLConnection.setDoOutput(true);

            httpURLConnection.setDoInput(true);

            // 擷取URLConnection對象對應的輸出流

            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

            // 發送請求參數

            printWriter.write(post);//post的參數 xx=xx&yy=yy

            // flush輸出流的緩沖

            printWriter.flush();

            System.out.println(httpURLConnection.getResponseCode());

            //開始擷取資料

            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            int len;

            byte[] arr = new byte[1024];

            while((len=bis.read(arr))!= -1){

                bos.write(arr,0,len);

                bos.flush();

            }

            bos.close();

            return bos.toString("utf-8");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    public static String postDownloadJsonHeader(String path,String post,String header){

    URL url = null;

    try {

    url = new URL(path);

    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

    httpURLConnection.setRequestMethod("POST");// 送出模式

    httpURLConnection.setRequestProperty("Content-Type", "application/json");

//    httpURLConnection.setRequestProperty("Authorization", header);

    // conn.setConnectTimeout(10000);//連接配接逾時 機關毫秒

    // conn.setReadTimeout(2000);//讀取逾時 機關毫秒

    // 發送POST請求必須設定如下兩行

    httpURLConnection.setDoOutput(true);

    httpURLConnection.setDoInput(true);

    // 擷取URLConnection對象對應的輸出流

    PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

    // 發送請求參數

    printWriter.write(post);//post的參數 xx=xx&yy=yy

    // flush輸出流的緩沖

    printWriter.flush();

    System.out.println(httpURLConnection.getResponseCode());

    //開始擷取資料

    BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    int len;

    byte[] arr = new byte[1024];

    while((len=bis.read(arr))!= -1){

    bos.write(arr,0,len);

    bos.flush();

    }

    bos.close();

    return bos.toString("utf-8");

    } catch (Exception e) {

    e.printStackTrace();

    }

    return null;

    }

    public static String  memberCodeClientget(String path,String Authorization) {

CloseableHttpClient httpCilent2 = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig.custom()

                .setConnectTimeout(5000)   //設定連接配接逾時時間

                .setConnectionRequestTimeout(5000) // 設定請求逾時時間

                .setSocketTimeout(5000)

                .setRedirectsEnabled(true)//預設允許自動重定向

                .build();

        HttpGet httpGet2 = new HttpGet(path);

        httpGet2.addHeader("Content-Type","application/json");

        httpGet2.setHeader("Authorization", Authorization);

        httpGet2.setConfig(requestConfig);

        String srtResult = "";

        try {

              HttpResponse httpResponse = httpCilent2.execute(httpGet2);

              System.out.println(httpResponse.getStatusLine().getStatusCode());

              String outstr = new String(EntityUtils.toString(httpResponse.getEntity()).getBytes("ISO-8859-1"),"UTF-8");

              srtResult = outstr;

              return srtResult;

        } catch (IOException e) {

            e.printStackTrace();

        }finally {

            try {

                httpCilent2.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

return srtResult;

}

    public static String doPost(String url,String jsonstr,String charset){

    CloseableHttpClient httpCilent =null ;

        HttpPost httpPost = null;

        String result = null;

        try{

        httpCilent = HttpClients.createDefault();

            httpPost = new HttpPost(url);

            httpPost.addHeader("Content-Type", "application/json");

            StringEntity se = new StringEntity(jsonstr);

            se.setContentType("text/json");

            se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));

            httpPost.setEntity(se);

            HttpResponse response = httpCilent.execute(httpPost);

            if(response != null){

                HttpEntity resEntity = response.getEntity();

                if(resEntity != null){

                    result = EntityUtils.toString(resEntity,charset);

                }

            }

        }catch(Exception ex){

            ex.printStackTrace();

        }

        return result;

    }

    public static String doPostaddHeader(String url,String jsonstr,String Header,String charset){

    CloseableHttpClient httpCilent =null ;

    HttpPost httpPost = null;

    String result = null;

    try{

    httpCilent = HttpClients.createDefault();

    httpPost = new HttpPost(url);

    httpPost.addHeader("Content-Type", "application/json");

    httpPost.setHeader("Authorization",Header);

    StringEntity se = new StringEntity(jsonstr);

    se.setContentType("text/json");

    se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));

    httpPost.setEntity(se);

    HttpResponse response = httpCilent.execute(httpPost);

    if(response != null){

    HttpEntity resEntity = response.getEntity();

    if(resEntity != null){

    result = EntityUtils.toString(resEntity,charset);

    }

    }

    }catch(Exception ex){

    ex.printStackTrace();

    }

    return result;

    }

這裡提供httpCilent 需要的兩個jar包  百度雲免費下載下傳

連結:https://pan.baidu.com/s/1hqW5Lfbj-yqg405vFC-Omw 密碼:ka5k