java获取外部接口数据(GET和POST请求)

一般使用步骤

首先使用HttpClient发送请求、接收响应,一般需要以下步骤。
HttpGet请求响应的一般步骤:
1). 创建HttpClient对象,可以使用HttpClients.createDefault()
2). 如果是无参数的GET请求,则直接使用构造方法HttpGet(String url)创建HttpGet对象即可;
如果是带参数GET请求,则可以先使用URIBuilder(String url)创建对象,再调用addParameter(String param, String value),或setParameter(String param, String value)来设置请求参数,并调用build()方法构建一个URI对象。只有构造方法HttpGet(URI uri)来创建HttpGet对象。
3). 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。调用HttpResponsegetAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponsegetEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()可以获取响应状态码。
4). 释放连接。

HttpPost请求响应的一般步骤:
1). 创建HttpClient对象,可以使用HttpClients.createDefault()
2). 如果是无参数的GET请求,则直接使用构造方法HttpPost(String url)创建HttpPost对象即可;
如果是带参数POST请求,先构建HttpEntity对象并设置请求参数,然后调用setEntity(HttpEntity entity)创建HttpPost对象。
3). 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。调用HttpResponsegetAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponsegetEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。通过调用getStatusLine().getStatusCode()可以获取响应状态码。
4). 释放连接。

具体实现:

构建一个Maven项目,引入如下依赖

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.5</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
/**
 *普通的GET请求
 */
public class DoGET {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet("http://www.baidu.com");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                //请求体内容
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\baidu.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            //相当于关闭浏览器
            httpclient.close();
        }
    }
}

import java.io.File;
import java.net.URI;
import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
 * 带参数的GET请求
 * 两种方式:
 *       1.直接将参数拼接到url后面 如:?wd=java
 *       2.使用URI的方法设置参数 setParameter("wd", "java")
 */
public class DoGETParam {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求的参数
        URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "java").build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
        //response 对象
        CloseableHttpResponse response = null;
        try {
            // 执行http get请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\baidu-param.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}
import org.apache.commons.io.FileUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;

/**
 * 常规post请求
 *    可以设置Header来伪装浏览器请求
 */
public class DoPOST {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/");
        //伪装浏览器请求
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\oschina.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 带有参数的Post请求
 * NameValuePair
 */
public class DoPOSTParam {
    public static void main(String[] args) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建http POST请求
        HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
        // 设置2个post参数,一个是scope、一个是q
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        parameters.add(new BasicNameValuePair("scope", "project"));
        parameters.add(new BasicNameValuePair("q", "java"));
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
        //伪装浏览器
        httpPost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                //内容写入文件
                FileUtils.writeStringToFile(new File("E:\\devtest\\oschina-param.html"), content, "UTF-8");
                System.out.println("内容长度:"+content.length());
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }
}

  • 1
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在Java中,你可以使用以下几种方式来请求外部接口: 1. 使用 `java.net` 包中的类,如 `URL` 和 `HttpURLConnection`。你可以使用这些类来发送 HTTP 请求获取响应。 2. 使用第三方库,如 Apache HttpClient、OkHttp 或 Retrofit。这些库都可以帮助你简化请求外部接口的流程,并提供了更丰富的功能。 下面是使用 `java.net` 包的示例代码: ``` URL url = new URL("http://www.example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); int responseCode = connection.getResponseCode(); if (responseCode == 200) { InputStream inputStream = connection.getInputStream(); // 读取响应内容 } else { // 处理错误 } ``` 如果你使用的是第三方库,可能会有所不同,但大体流程是类似的。 ### 回答2: 在Java请求外部接口可以使用Java提供的相关库和工具来实现。主要有以下几种方式: 1. 使用HttpURLConnection类:Java提供了HttpURLConnection类来发送HTTP请求,可以通过该类发送GET、POST请求获取接口返回的数据。可以使用该类来建立连接、设置请求方法、添加请求头、发送请求获取响应等。 2. 使用HttpClient类:HttpClient是Apache提供的一个开源工具包,用于发送HTTP请求。可以使用该工具包发送GET、POST请求,设置请求参数、请求头等,并获取接口返回的数据。 3. 使用第三方库OkHttp:OkHttp是Square公司开发的一个优秀的HTTP客户端库。它简化了与网站的通信过程,提供了易于使用的API来处理HTTP请求和响应。可以使用OkHttp发送GET、POST请求,设置请求参数、请求头等,并获取接口返回的数据。 4. 使用RestTemplate类:RestTemplate是Spring框架中提供的一个用于访问Rest服务的模板类,它封装了HTTP请求的处理逻辑。可以使用RestTemplate发送GET、POST请求,并通过设置请求参数、请求头等来访问外部接口。 以上是几种常见的在Java请求外部接口的方式。根据项目的需求和开发的场景,可以选择合适的方式来实现数据请求和处理。 ### 回答3: Java请求外部接口的方式有多种。其中比较常见的方式是使用Java的网络编程库来发送HTTP请求。 首先,需要引入Java的网络编程相关的库,如Java自带的URLConnection类或者第三方库如HttpClient等。 然后,可以使用以下步骤来请求外部接口: 1. 构建URL对象:使用接口的URL地址创建一个URL对象。 2. 打开连接:通过URL对象的openConnection方法打开一个连接对象,得到URLConnection实例。 3. 设置请求属性:如果需要,可以设置一些请求头信息,如User-Agent、请求方法、超时时间等。 4. 发送请求:通过调用URLConnection对象的connect()方法发送请求。 5. 获取响应:可以通过getResponseCode()方法获取响应的状态码,通过getInputStream()方法获取响应的输入流,从而获取返回的数据。 6. 处理响应:根据接口的返回格式进行解析和处理,可以使用Java内置的JSON库或第三方库让数据解析更加方便。 7. 关闭连接:最后,一定要关闭连接,可以通过调用URLConnection对象的disconnect()方法来关闭连接。 总之,使用Java请求外部接口需要通过网络编程库构建URL对象,设置请求方式和请求头,发送请求获取响应,最后对响应进行处理和关闭连接。具体的实现和处理方式会根据接口的具体要求和返回格式而有所不同。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值