java後台訪問url串連——HttpClients

來源:互聯網
上載者:User

標籤:

java後台訪問url,並傳遞資料——通過httpclient方式

需要的包,包可能多幾個額外的,如果無用或者衝突刪除即可,httpclient是使用的是4.4.1的版本:http://download.csdn.net/detail/myfmyfmyfmyf/8894191

1、無參數傳遞,以開發為例,後台訪問url串連獲得全部的人員列表

/** * 擷取全部人員列表 * @return */    public  JSONObject getAllEmployee(){    //擷取號    String token=getTokenFromWx();     String dep_root=ROOT_DEP;//跟部門樹 try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost= new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token="+token+"&department_id="+dep_root+"&fetch_child="+FETCH_CHILD+"&status="+STATE); // Create a custom response handler ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {//成功調用串連後,對返回資料進行的操作                public JSONObject handleResponse(                        final HttpResponse response) throws ClientProtocolException, IOException {                    int status = response.getStatusLine().getStatusCode();                    if (status >= 200 && status < 300) {                    //獲得調用成功後  返回的資料                        HttpEntity entity = response.getEntity();                        if(null!=entity){                        String result= EntityUtils.toString(entity);                            //根據字串產生JSON對象                    JSONObject resultObj = JSONObject.fromObject(result);                    return resultObj;                        }else{                        return null;                        }                    } else {                        throw new ClientProtocolException("Unexpected response status: " + status);                    }                }            };          //返回的json對象            JSONObject responseBody = httpclient.execute(httpPost, responseHandler);            //System.out.println(responseBody);            return responseBody;  }catch (Exception e) {e.printStackTrace();return null;}           }


 

2、有參數傳遞,以開發為例,後台訪問url主動發送訊息(json資料),httpClient通過設定StringEntity對象傳遞

/**   * 主動發送訊息   * @param mess   * @return   */  public  boolean sendReqMsg(ReqBaseMessage mess){  //訊息json格式  String jsonContext=mess.toJsonStr();  //System.out.println(jsonContext);  //獲得token  String token=getTokenFromWx(); boolean flag=false; try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost= new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+token); //發送json格式的資料 StringEntity myEntity = new StringEntity(jsonContext,    ContentType.create("text/plain", "UTF-8")); //設定需要傳遞的資料 httpPost.setEntity(myEntity); // Create a custom response handler            ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {            //對訪問結果進行處理                public JSONObject handleResponse(                        final HttpResponse response) throws ClientProtocolException, IOException {                    int status = response.getStatusLine().getStatusCode();                    if (status >= 200 && status < 300) {                        HttpEntity entity = response.getEntity();                        if(null!=entity){                        String result= EntityUtils.toString(entity);                            //根據字串產生JSON對象                    JSONObject resultObj = JSONObject.fromObject(result);                    return resultObj;                        }else{                        return null;                        }                    } else {                        throw new ClientProtocolException("Unexpected response status: " + status);                    }                }            };          //返回的json對象            JSONObject responseBody = httpclient.execute(httpPost, responseHandler);            System.out.println(responseBody);            int result= (Integer) responseBody.get("errcode");            if(0==result){            flag=true;            }else{            flag=false;            }httpclient.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} return flag;}


3、傳遞圖片、檔案等媒體資訊,還是以開發為例

/**     * 檔案上傳到伺服器     * @param fileType 檔案類型 媒體檔案類型,分別有圖片(image)、語音(voice)、視頻(video),普通檔案(file)     * @param filePath 檔案路徑     * @return JSONObject     * @throws Exception     */    public  JSONObject send(String fileType, String filePath) throws Exception {          String result = null;          File file = new File(filePath);          if (!file.exists() || !file.isFile()) {              throw new IOException("檔案不存在");          }          String token=getTokenFromWx();        /**         * 第一部分         */          URL urlObj = new URL("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+ token         + "&type="+fileType+"");                   HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();          con.setRequestMethod("POST"); // 以Post方式提交表單,預設get方式          con.setDoInput(true);          con.setDoOutput(true);          con.setUseCaches(false); // post方式不能使用緩衝          // 佈建要求頭資訊          con.setRequestProperty("Connection", "Keep-Alive");          con.setRequestProperty("Charset", "UTF-8");          // 設定邊界          String BOUNDARY = "----------" + System.currentTimeMillis();          con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY);          // 請求本文資訊          // 第一部分:          StringBuilder sb = new StringBuilder();          sb.append("--"); // 必須多兩道線          sb.append(BOUNDARY);          sb.append("\r\n");          sb.append("Content-Disposition: form-data;name=\"media\";filename=\""+ file.getName() + "\"\r\n");          sb.append("Content-Type:application/octet-stream\r\n\r\n");          byte[] head = sb.toString().getBytes("utf-8");          // 獲得輸出資料流          OutputStream out = new DataOutputStream(con.getOutputStream());          // 輸出表頭          out.write(head);          // 檔案本文部分          // 把檔案已流檔案的方式 推入到url中          DataInputStream in = new DataInputStream(new FileInputStream(file));          int bytes = 0;          byte[] bufferOut = new byte[1024];          while ((bytes = in.read(bufferOut)) != -1) {          out.write(bufferOut, 0, bytes);          }          in.close();          // 結尾部分          byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定義最後資料分隔線          out.write(foot);          out.flush();          out.close();          StringBuffer buffer = new StringBuffer();          BufferedReader reader = null;          try {          // 定義BufferedReader輸入資料流來讀取URL的響應          reader = new BufferedReader(new InputStreamReader(con.getInputStream()));          String line = null;          while ((line = reader.readLine()) != null) {          //System.out.println(line);          buffer.append(line);          }          if(result==null){          result = buffer.toString();          }          } catch (IOException e) {          System.out.println("發送POST請求出現異常!" + e);          e.printStackTrace();          throw new IOException("資料讀取異常");          } finally {          if(reader!=null){          reader.close();          }          }          JSONObject jsonObj =JSONObject.fromObject(result);          return jsonObj;      }


 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

java後台訪問url串連——HttpClients

聯繫我們

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