java http请求并返回字符串

本文提供了一个使用Java实现HTTP POST请求的具体示例。通过构造URL并设置必要的HTTP头信息,文章展示了如何发送带有参数的数据,并从服务器接收响应。

public static String getHttpData(String url, String data) throws Exception{
        StringBuffer resultData = new StringBuffer();
        URL postUrl = new URL(url);// url到?
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
        osw.write(data); // data是url问号之后的所有参数集合
        osw.flush();
        osw.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            resultData.append(line);
        }
        reader.close();
        return resultData.toString();
    }

Java 中接收处理 HTTP POST 请求返回的 JSON 字符串,通常涉及客户端发送请求解析响应内容。可以使用多种方式实现该功能,例如 Apache HttpClient、OkHttp 或 Spring 的 `RestTemplate`。以下是使用 Apache HttpClient 接收解析 JSON 响应的完整实现。 ### 使用 Apache HttpClient 接收解析 JSON 响应 发送 POST 请求后,可以通过 `EntityUtils.toString()` 获取响应体字符串,再使用 `org.json` 或 `Gson` 等库解析 JSON 数据。 ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; 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 JsonPostResponseHandler { public static void main(String[] args) { String url = "https://example.com/api/login"; String jsonInput = "{\"username\":\"test\",\"password\":\"password\"}"; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json"); httpPost.setEntity(new StringEntity(jsonInput)); try (CloseableHttpResponse response = httpClient.execute(httpPost)) { HttpEntity entity = response.getEntity(); if (entity != null) { String jsonResponse = EntityUtils.toString(entity); System.out.println("Raw JSON Response: " + jsonResponse); // 解析 JSON 字符串 JSONObject jsonObject = new JSONObject(jsonResponse); String token = jsonObject.getString("token"); System.out.println("Parsed Token: " + token); } } } catch (Exception e) { e.printStackTrace(); } } } ``` ### 依赖配置 如果使用 `org.json` 解析 JSON 字符串,需要在 `pom.xml` 中添加以下依赖: ```xml <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20210307</version> </dependency> ``` 如果使用 `Gson`,可以添加: ```xml <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency> ``` ### 异常处理 处理 HTTP 请求时,应捕获异常进行日志记录或重试机制,以应对网络中断、超时或服务器错误等情况。可以使用 `try-with-resources` 语句确保资源释放,同时对 `HttpResponse` 进行非空检查以避免空指针异常 [^1]。 ### 示例 JSON 响应 ```json { "token": "abc123xyz", "status": "success" } ``` ### 相关处理方式 - 使用 `RestTemplate` 发送请求直接返回 `ResponseEntity<String>` 以获取原始 JSON 字符串。 - 在 Spring Boot 中,可以结合 `@RequestBody` 接收请求返回 JSON 字符串 [^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值