tongshen9095 / JobRecommendation

0 stars 0 forks source link

HttpClient Library #6

Open tongshen9095 opened 4 years ago

tongshen9095 commented 4 years ago

Example 1

// Create a HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
// Create a HTTP request: specify method and URL
HttpGet httpGet = new HttpGet("http://targethost/homepage");
// send the request to obtain response
CloseableHttpResponse response1 = httpclient.execute(httpGet);

// The underlying HTTP connection is still held by the response object
// to allow the response content to be streamed directly from the network socket.
// In order to ensure correct deallocation of system resources
// the user MUST call CloseableHttpResponse#close() from a finally clause.
// Please note that if response content is not fully consumed the underlying
// connection cannot be safely re-used and will be shut down and discarded
// by the connection manager. 
try {
    // get the status of the response
    System.out.println(response1.getStatusLine());
    // get the response body
    HttpEntity entity1 = response1.getEntity();

    // do something useful with the response body
    // and ensure it is fully consumed
    /*
     * a client object can send multiple requests
     * tell the client we have obtained the response
     * clear the buffer
     * and the client can send another request
     */
    EntityUtils.consume(entity1);
} finally {
    response1.close();
}

// the second request
HttpPost httpPost = new HttpPost("http://targethost/login");
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username", "vip"));
nvps.add(new BasicNameValuePair("password", "secret"));
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response2 = httpclient.execute(httpPost);

try {
    System.out.println(response2.getStatusLine());
    HttpEntity entity2 = response2.getEntity();

    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity2);
} finally {
    response2.close();
}
tongshen9095 commented 4 years ago
// can close the httpclient to release resource
httpclient.close()

try-catch-finally, stackoverflow

Screen Shot 2020-07-23 at 2 10 43 PM
tongshen9095 commented 4 years ago

Example 2

// step1: Create a HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();

try {
   // step2: Create a HTTP request: specify method and URL
    HttpGet httpget = new HttpGet("http://httpbin.org/");
    System.out.println("Executing request " + httpget.getRequestLine());

    /*
     * Create a custom response handler
     * do not need to manually consume the entity and close the response
     * inheritance ResponseHandler<string>, parent class
    */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(
                final HttpResponse response) throws ClientProtocolException, IOException {
            // return the response body
            int status = response.getStatusLine().getStatusCode();
            // status code between 200 and 300 indicates the request successed
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        }

    };

    /*
     * step3: get response body directly via a custom response handler
     * http.execute(httpget, responseHandler) call consume and close in the parent class
    */
    String responseBody = httpclient.execute(httpget, responseHandler);
    System.out.println("----------------------------------------");
    System.out.println(responseBody);
} finally {
    httpclient.close();
}
tongshen9095 commented 4 years ago

conditional operator :?

int count = isHere ? getHereCount(index) : getAwayCount(index);

is a shorthand of

if (isHere) {
    count = getHereCount(index);
} else {
    count = getAwayCount(index);
}

if doSomething() and doSomethingElse() are void methods, we cannot use the shorthand

tongshen9095 commented 4 years ago

Implement

public JSONArray search(double lat, double lon, String keyword) {
    // corner case: user does not provide keyword, then use the default
    if (keyword == null) {
        keyword = DEFAULT_KEYWORD;
    }
    try {
        // encode the keyword
        keyword = URLEncoder.encode(keyword, "UTF-8");
    } 
    catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    // step1: : Create a HttpClient object
    CloseableHttpClient httpclient = HttpClients.createDefault();
    // step2: Create a HTTP request: specify method and URL
    String url = String.format(URL_TEMPLATE, keyword, lat, lon);
    HttpGet httpget = new HttpGet(url);

    /*
     * Create a custom response handler
     * return JSONArray
    */
    ResponseHandler<JSONArray> responseHandler = new ResponseHandler<JSONArray>() {

        @Override
        public JSONArray handleResponse(final HttpResponse response) throws IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status != 200) {
                return new JSONArray();
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return new JSONArray();
            }
            String responseBody = EntityUtils.toString(entity);
            return new JSONArray(responseBody);
        }
    };

    try {
        // step3: get response body directly via a custom response handler
        JSONArray array = httpclient.execute(httpget, responseHandler);
        return array;
    } 
    catch (ClientProtocolException e) {
        e.printStackTrace();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }
    return new JSONArray();
}
tongshen9095 commented 4 years ago

JSON is a format for string, not a JSONArray, so we need to convert string to JSONArray the response contains multiple JSONObjets