1. Java
  2. PHP

Apache HttpComponents快速上手

The World’s Largest Open Source Foundation

    • 200M+ lines of code in stewardship
    • 1,058,321,099 lines of code committed
    • 3,022,836 code commits
    • 730 individual ASF Members
    • 7,000 Apache code committers
    • All volunteer community
  • 350+ Projects and Initiatives
  • 300+ Top-Level Projects
  • 52 podlings in the Apache Incubator

$20B+ worth of Apache Open Source software products are made available to the public-at-large at 100% no cost, and benefit billions of users around the world.

我是从使用httpd开始才了解Apache的,而现在越来越多地方都能看到Apache的身影。感谢 ASF 为开源事业做出的贡献。

1.创建测试API

这里就简单的用PHP写一个脚本来响应一个JSON数据

<?php
header('Content-Type:application/json');
$data = array(
	"status" => 200,
	"user" => "Michael Jiang",
	"ip" => "127.0.0.1"
	);
echo json_encode($data);
?>

测试调用地址:

http://api.sencom.top/android_test_point

浏览器打开没有问题。

2.下载HttpComponents Downloads

项目首页:http://hc.apache.org

下载完成后将压缩包里面的jar文件移动到Java项目文件夹下的lib文件夹中

这里我还下载了json (就是json官网提供的java语言分类中的第一个解析库)

3.启动Eclipse 导入扩展库

导入方法:

右击项目-》Build Path-》configure build path-》Add External JARs即可

QuickStart.java

package top.sencom.httpclient;

import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class QuickStart {

    public static void main(String[] args) throws Exception {
    	byte[] b = new byte[1024];
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet("http://api.sencom.top/android_test_point");
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            try {
                System.out.println(response1.getStatusLine());
                HttpEntity entity = response1.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println(result);
                JSONObject js = new JSONObject(result);
                Set<String> s = js.keySet();
                for(String it : s) {
                	System.out.println("key : "+it+" value : " + js.get(it).toString());
                }
                EntityUtils.consume(entity);
            } finally {
                response1.close();
            }
        } finally {
            httpclient.close();
        }
      
    }
}

改写自:http://hc.apache.org/httpcomponents-client-4.5.x/quickstart.html

运行结果如下: