httpclien

本文介绍了一个使用Android进行HTTP GET和POST请求的具体示例。通过示例代码展示了如何利用Apache HttpClient发起网络请求并处理响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


android {
useLibrary 'org.apache.http.legacy'
}

 

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);








    }
 
    public void btnForGet(View view){

        new Thread(){
            @Override
            public void run() {
                httpClientForGet();
            }
        }.start();



    }

    public void btnForPost(View view){


        new Thread(){
            @Override
            public void run() {
                httpClientForPost("52cb54f14bc3bbcd9a96e1d13ee0cf2b");
            }
        }.start();


    }




   
    private void httpClientForGet(){

        try {
            //打开浏览器
            HttpClient httpClient = new DefaultHttpClient();
            //填一下地址
            HttpGet httpGet = new HttpGet("http://japi.juhe.cn/health_knowledge/categoryList?key=eb033dfcf95c03f9f451f6973049e6be");
            //敲回车,并等待服务器响应
            HttpResponse httpResponse = httpClient.execute(httpGet);

            //getStatusLine() 得到状态行  getStatusCode() 得到状态码
            int code = httpResponse.getStatusLine().getStatusCode();

            if(code == 200){
                //getEntity() 得到响应实体
                InputStream is = httpResponse.getEntity().getContent();
                //字节流转字符串
                String result = StreamTools.readFromNetWork(is);

                System.out.println("HttpClientGet结果 : "+result);

            }






        } catch (Exception e) {
            e.printStackTrace();
        }


    }


   
    private void httpClientForPost(String key){

        try {
            //1.打开浏览器
            HttpClient httpClient = new DefaultHttpClient();
            //2.填一下地址
            HttpPost httpPost = new HttpPost("http://v.juhe.cn/expressonline/getCarriers.php");


            //设置请求参数
            List params = new ArrayList();
            //往集合添加请求参数
            params.add(new BasicNameValuePair("key",key));
            params.add(new BasicNameValuePair("ex_category","顺丰"));
            //params.add(new BasicNameValuePair())

            httpPost.setEntity(new UrlEncodedFormEntity(params));
            //3.敲回车,等待服务器响应
            HttpResponse httpResponse = httpClient.execute(httpPost);

            //4.得到服务器响应状态码
            int code = httpResponse.getStatusLine().getStatusCode();


            if(code == 200){//判断服务器是否成功响应
                //得到服务器的响应内容
                InputStream is = httpResponse.getEntity().getContent();
                String result = StreamTools.readFromNetWork(is);

                System.out.println("结果 --> "+result);

            }




        } catch (Exception e) {
            e.printStackTrace();
        }


    }




}

在 Feign 中使用 HttpClient 连接池可以提高性能和资源利用率,避免重复创建和关闭连接。下面是整合的步骤: 1. 添加依赖 在 pom.xml 中添加以下依赖: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> ``` 2. 配置 HttpClient 在 Spring Boot 中,可以使用 HttpClientBuilder 来构建 HttpClient,并配置连接池参数: ```java @Configuration public class HttpClientConfig { @Value("${httpclient.max-total}") private int maxTotal; @Value("${httpclient.default-max-per-route}") private int defaultMaxPerRoute; @Bean public CloseableHttpClient httpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(maxTotal); connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); return HttpClientBuilder.create() .setConnectionManager(connectionManager) .build(); } } ``` 其中,maxTotal 表示连接池最大连接数,defaultMaxPerRoute 表示每个路由(域名)最大连接数。 3. 配置 Feign 在 Feign 中配置 HttpClient,需要实现 HttpClient 的 Client 接口,具体如下: ```java public class HttpClientFeignClient implements Client { private final CloseableHttpClient httpClient; public HttpClientFeignClient(CloseableHttpClient httpClient) { this.httpClient = httpClient; } @Override public Response execute(Request request, Request.Options options) throws IOException { HttpClientContext context = HttpClientContext.create(); HttpUriRequest httpUriRequest = toHttpUriRequest(request); CloseableHttpResponse httpResponse = httpClient.execute(httpUriRequest, context); return toResponse(httpResponse); } private HttpUriRequest toHttpUriRequest(Request request) { String method = request.method(); String url = request.url(); Request.Body body = request.body(); HttpEntityEnclosingRequestBase httpUriRequest; switch (method) { case "GET": httpUriRequest = new HttpGet(url); break; case "POST": httpUriRequest = new HttpPost(url); break; case "PUT": httpUriRequest = new HttpPut(url); break; case "DELETE": httpUriRequest = new HttpDelete(url); break; default: throw new UnsupportedOperationException("unsupported http method: " + method); } if (body != null) { httpUriRequest.setEntity(new ByteArrayEntity(body.asBytes())); } return httpUriRequest; } private Response toResponse(CloseableHttpResponse httpResponse) throws IOException { int statusCode = httpResponse.getStatusLine().getStatusCode(); String reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); Map<String, Collection<String>> headers = new HashMap<>(); for (Header header : httpResponse.getAllHeaders()) { String name = header.getName(); String value = header.getValue(); headers.computeIfAbsent(name, k -> new ArrayList<>()).add(value); } Response.Builder builder = Response.builder() .status(statusCode) .reason(reasonPhrase) .headers(headers); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); byte[] bodyData = ByteStreams.toByteArray(inputStream); builder.body(bodyData); } return builder.build(); } } ``` 最后,在 Feign 的配置类中,使用上述实现类作为 Client: ```java @Configuration public class FeignConfig { @Autowired private CloseableHttpClient httpClient; @Bean public Client feignClient() { return new HttpClientFeignClient(httpClient); } } ``` 这样就完成了 Feign 整合 HttpClient 连接池的配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值