Java background access url Connection -- HttpClients
Access the url in the java background and transmit data-using httpclient
1. There is no parameter transfer. Taking Development as an example, you can access the url Connection in the background to obtain a list of all people.
/*** Get all personnel list * @ return */public JSONObject getAllEmployee () {// get the String token = getTokenFromWx (); String dep_root = ROOT_DEP; // follow the Department tree 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
ResponseHandler = new ResponseHandler
() {// The Operation public JSONObject handleResponse (final HttpResponse response) throws ClientProtocolException, IOException {int status = response after the connection is successfully called. getStatusLine (). getStatusCode (); if (status >=200 & status <300) {// get the data returned after successful call HttpEntity entity = response. getEntity (); if (null! = Entity) {String result = EntityUtils. toString (entity); // generate the JSON object JSONObject resultObj = JSONObject Based on the string. fromObject (result); return resultObj;} else {return null ;}} else {throw new ClientProtocolException (Unexpected response status: + status );}}}; // return json object JSONObject responseBody = httpclient.exe cute (httpPost, responseHandler); // System. out. println (responseBody); return responseBody;} catch (Exception e) {e. printStackTrace (); return null ;}}
2. There is parameter transfer. Taking Development as an example, the background access url actively sends messages (json data), and The httpClient transmits messages by setting the StringEntity object.
/*** Actively send the message * @ param mess * @ return */public boolean sendReqMsg (ReqBaseMessage mess) {// message json Format String jsonContext = mess. toJsonStr (); // System. out. println (jsonContext); // get 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); // send the json format data StringEntity myEntity = new StringEntity (jsonContext, ContentType. create (text/plain, UTF-8); // sets the data to be passed httpPost. setEntity (myEntity); // Create a custom response handler ResponseHandler
ResponseHandler = new ResponseHandler
() {// Process access results 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); // generate the JSON object JSONObject resultObj = JSONObject Based on the string. fromObject (result); return resultObj;} else {return null ;}} else {throw new ClientProtocolException (Unexpected response status: + status );}}}; // The returned json object JSONObject responseBody = httpclient.exe cute (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. Transfer media information such as images and files, or take development as an example.
/*** Upload the file to the server * @ param fileType specifies the media file type, which can be image, voice, video, or file) * @ param filePath file path * @ 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 (file does not exist);} String token = getTokenFromWx ();/*** first part */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); // submit the form in Post mode. The default get method is con. setDoInput (true); con. setDoOutput (true); con. setUseCaches (false); // The cache cannot be used in post mode. // set the request header information con. setRequestProperty (Connection, Keep-Alive); con. setRequestProperty (Charset, UTF-8); // set the BOUNDARY String BOUNDARY = ---------- + System. currentT ImeMillis (); con. setRequestProperty (Content-Type, multipart/form-data; boundary = + BOUNDARY); // Request body information // Part 1: StringBuilder sb = new StringBuilder (); sb. append (--); // there must be two more lines of sb. append (BOUNDARY); sb. append (); sb. append (Content-Disposition: form-data; name = media; filename = + file. getName () + \ r); sb. append (Content-Type: application/octet-stream); byte [] head = sb. toString (). getBytes (UTF-8); // get the output stream OutputStream out = new DataOutputStream (con. getOutputStream (); // output header out. write (head); // part of the file body // push the stream file into the 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 (); // the end part of byte [] foot = (-- + BOUNDARY + --). getBytes (UTF-8); // defines the last data separation line out. write (foot); out. flush (); out. close (); StringBuffer buffer = new StringBuffer (); BufferedReader reader = null; try {// define the BufferedReader input stream to read the URL response reader = new BufferedReader (new InputStreamReader (con. getInputStream (); String line = null; while (line = reader. readLi Ne ())! = Null) {// System. out. println (line); buffer. append (line);} if (result = null) {result = buffer. toString () ;}} catch (IOException e) {System. out. println (an exception occurred when sending the POST request! + E); e. printStackTrace (); throw new IOException (Data Reading exception);} finally {if (reader! = Null) {reader. close () ;}} JSONObject jsonObj = JSONObject. fromObject (result); return jsonObj ;}