CISC 3120 C24: Web API: Passing Arguments and Parsing Returns

[Pages:32]CISC 3120

C24: Web API: Passing Arguments and Parsing

Returns

Hui Chen Department of Computer & Information Science

CUNY Brooklyn College

5/7/2018

CUNY | Brooklyn College

1

Outline

? Parsing arguments/data to Web server ? Parsing returned value/data from Web

server

Path variables & request parameters

HTTP

Web client

Web server

JSON/XML objects

5/7/2018

CUNY | Brooklyn College

2

Passing Arguments via URL

? URL syntax

Contains arguments

? scheme://authority[path][?query][#fragment]

5/7/2018

Path variables Query parameters (request parameters)

CUNY | Brooklyn College

3

Passing Argument via Request Body

header

? Request with the HTTP POST method

POST /index.html HTTP/1.1 Request method, URN, protocol version User-Agent: Java Web Client Host: localhost:61235 Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2 Connection: keep-alive

Two blank lines

......

5/7/2018

Contains arguments (request parameters)

CUNY | Brooklyn College

4

body

Passing Arguments

? Use .HttpURLConnection

? Path variables ? Request parameters

? In URL (with the HTTP GET method) ? In HTTP request Body (with the HTTP POST method)

? Note

? Libraries and 3rd Party APIs may provide convenient methods or mechanisms

? Example: jdk.incubator.http.HttpRequest

? "incubator" are Java features that are under development

? Example: org.apache.http.HttpRequest

? Apache HTTP client API

5/7/2018

CUNY | Brooklyn College

5

Path Variables: Example

? Use String.format(...) method ? URL-encode strings for compatibility

? Not the entire URL! ? .URLEncoder

? Example

? final static String WEB_API_FMT = ""; ? String itemName = "blue moon"; int type = 5; ? String urlResource = String.format(WEB_API_FMT,

URLEncoder.encode(itemName, StandardCharsts.UTF_8.name()), type); ? Example: the Address-auto-fill-by-zipcode example

5/7/2018

CUNY | Brooklyn College

6

Request Parameters

? General guideline for preparing the parameters

? Form key-value pairs, separate with "&" ? Send the key-value pairs to the server ? Examples

? Using a Map data structure

? A map data structure is a list of key-value pair ? URL-encode and key and value

5/7/2018

CUNY | Brooklyn College

7

URL Query Component

? URL syntax

? scheme://authority[path][?query][#fragment]

Query parameters (request parameters)

? Concatenate the prepared parameters (namevalue pairs) with the URL

? Example:

? apiResource = url + "?" + preparedQuery;

5/7/2018

CUNY | Brooklyn College

8

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download