Java Post请求 传递Json参数

本文提供了两个Java示例,展示了如何向服务器发送JSON格式的数据及如何从服务器接收JSON格式的数据。示例包括了使用HttpURLConnection进行POST请求的方法,以及如何解析返回的JSON数组。

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

1,给接口传递json格式的数据

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import net.sf.json.JSONObject;

public class AppAddTest {
    public static final String ADD_URL = "http://192.168.1.1:8080/*.controller/*.action";
    public static void appadd() {
        try {
            URL url = new URL(ADD_URL);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("connection", "Keep-Alive");
            //connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
            connection.connect();
            //POST请求
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());
            JSONObject obj = new JSONObject();
            String message = java.net.URLEncoder.encode("哈哈哈","utf-8");
            obj.element("detail", "df");
            obj.element("TEXT1", "asd");
            obj.element("TEXT2", message);

            out.writeBytes("data="+obj.toString());
            System.out.println("data="+obj.toString());
            out.flush();
            out.close();
            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            System.out.println(sb);
            reader.close();
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        appadd();
    }

}

2.从接口获取json格式数据

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.springframework.web.HttpRequestHandler;
public class JAVAURL {

    /**
     * @param args
     */
    public static void main(String[] args) {
        String url = "http://192.168.1.1:8080/*.controller.do/*.action";
           System.out.println("URL:"+url);
           StringBuffer json = new StringBuffer();
            try {
                //实例一个url和URLConnection
                URL oracle = new URL(url);
                //打开链接
                URLConnection yc = oracle.openConnection();
                //输入流作参数传进InputStreamReader并用BufferedReader接受
                BufferedReader in = new BufferedReader(new InputStreamReader(
                                            yc.getInputStream()));
                String inputLine = null;
                //一直读到空,并设置流编码是UTF8
                while ( (inputLine = in.readLine()) != null) {
                    json.append(new String(inputLine.getBytes(),"GBK"));
                }
                //记得关闭连接
                in.close();
            } catch (Exception e)  {
                e.printStackTrace();
            }
        try {
            JSONArray jn =  JSONArray.fromObject(json.toString());
            if(jn.size()>0){
            for (int i = 0; i < jn.size(); i++) {
                JSONObject jo = (JSONObject) jn.get(i);
                System.out.println(jo.get("id"));
                System.out.println(jo.get("fdName"));
            }
            System.out.println(jn);
            }
            System.out.println("数据大小:"+jn.size());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接超时!");
        }
    }

}

博文转自:http://www.cnblogs.com/taotingkai/p/6639078.html


### 使用HttpClient发送POST请求传递JSON数据 当使用 `HttpClient` 发送 POST 请求传递 JSON 数据时,可以按照如下方式构建请求。这涉及到创建一个带有适当头信息的 `HttpPost` 对象,并设置实体内容为 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; public class HttpClientExample { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost("https://example.com/api/resource"); String json = "{\"name\":\"John\", \"age\":30}"; StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); CloseableHttpResponse response = httpClient.execute(httpPost); try { System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // do something useful with the response body System.out.println(EntityUtils.toString(resEntity)); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpClient.close(); } } } ``` 此代码片段展示了如何通过 Apache HttpClient 库来执行带 JSON 负载的 HTTP POST 请求[^1]。注意这里设置了 Content-Type 和 Accept 头部字段为 application/json 以指明所期望的内容类型[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值