Calling JD.com News API with Java HttpClient – Complete Code Walkthrough

This article demonstrates how to use Java HttpClient to call the free JD.com Wanxiang news channel API, providing a fully commented implementation, response handling methods, and a sample JSON output for developers who need a clear, unwrapped example.

FunTester
FunTester
FunTester
Calling JD.com News API with Java HttpClient – Complete Code Walkthrough

I discovered a free news channel API on JD.com Wanxiang while practicing with HttpClient, so I implemented a plain Java version with detailed comments because the official documentation only offers wrapped Java examples.

API Request Code

public void testDemo() throws JSONException, UnsupportedOperationException, IOException {
    String url = "https://way.jd.com/jisuapi/get"; // set API endpoint
    // set parameters
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("channel", channel[1]);
    jsonObject.put("num", "5");
    jsonObject.put("start", "0");
    jsonObject.put("appkey", APPKEY);
    String uri = changeJsonToArguments(jsonObject); // build query string
    HttpGet get = new HttpGet(url + uri); // create GET request
    JSONObject response = getHttpResponse(get); // execute request
    output(response); // print response entity
    testOver(); // close client
}

The getHttpResponse method (core logic shown below) handles request validation, header logging, timing, response parsing, and error handling.

Response Retrieval Method

public static JSONObject getHttpResponse(HttpRequestBase request) {
    if (!isRightRequest(request)) return new JSONObject();
    beforeRequest(request);
    JSONObject res = new JSONObject();
    RequestInfo requestInfo = new RequestInfo(request);
    if (HEADER_KEY) output("===========request header===========", Arrays.asList(request.getAllHeaders()));
    long start = Time.getTimeStamp();
    try (CloseableHttpResponse response = ClientManage.httpsClient.execute(request)) {
        long end = Time.getTimeStamp();
        long elapsed_time = end - start;
        if (HEADER_KEY) output("===========response header===========", Arrays.asList(response.getAllHeaders()));
        int status = getStatus(response, res);
        JSONObject setCookies = afterResponse(response);
        String content = getContent(response);
        int data_size = content.length();
        res.putAll(getJsonResponse(content, setCookies));
        int code = iBase == null ? -2 : iBase.checkCode(res, requestInfo);
        MySqlTest.saveApiTestDate(requestInfo, data_size, elapsed_time, status, getMark(), code, LOCAL_IP, COMPUTER_USER_NAME);
    } catch (Exception e) {
        logger.warn("Failed to obtain request response!", e);
        if (!SysInit.isBlack(requestInfo.getHost()))
            new AlertOver("Interface request failed", requestInfo.toString(), requestInfo.getUrl(), requestInfo).sendSystemMessage();
    } finally {
        HEADER_KEY = false;
        if (!SysInit.isBlack(requestInfo.getHost())) {
            if (requests.size() > 9) requests.removeFirst();
            requests.add(request);
        }
    }
    return res;
}

Response Parsing Helper

public static String parseResponse(CloseableHttpResponse response) {
    HttpEntity entity = response.getEntity(); // get response entity
    String content = EMPTY;
    try {
        content = EntityUtils.toString(entity, DEFAULT_CHARSET); // read entity as string
        EntityUtils.consume(entity); // release resources
    } catch (Exception e1) {
        logger.warn("Exception while parsing response entity!", e1);
    }
    return content;
}

The API returns a JSON object similar to the following (formatted for readability):

{
  "code":"10000",
  "charge":false,
  "msg":"查询成功",
  "result":{
    "msg":"ok",
    "result":{
      "num":"5",
      "channel":"新闻",
      "list":[{
        "src":"澎湃新闻",
        "weburl":"http://news.sina.com.cn/c/nd/2017-08-26/doc-ifykiqfe1818402.shtml",
        "time":"2017-08-26 17:08",
        "pic":"",
        "title":"北京市食药监局:海底捞限期一个月实现后厨公开",
        "category":"news",
        "content":"<p>Original title: ...</p>",
        "url":"http://news.sina.cn/gn/2017-08-26/detail-ifykiqfe1818402.d.html?..."
      }]
    }
  },
  "status":"0"
}

This example shows how to construct the request, handle headers and timing, parse the JSON response, and log relevant metrics, providing a ready‑to‑use reference for developers integrating JD.com’s free news API.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendAPIJD.comNewsAPI
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.