Java 通过HttpURLConnection Post方式提交json,并从服务端返回json数据

这个技术和xml差不过,主要是服务端代码稍微修改,客户端代码修改部分传递参数就可以完成,但在之前需要导入json所需要的jar包。
PostJson.java代码

package PostPager;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PostJson {
    public static void main(String args[])
    {
        try {

            JSONObject  obj = new JSONObject();
                    obj.append("app_name", "全民大讨论");
                    obj.append("app_ip", "10.21.243.234");
                    obj.append("app_port", 8080);
                    obj.append("app_type", "001");
                    obj.append("app_area", "asd");

                System.out.println(obj);
            // 创建url资源
            URL url = new URL("http://119.29.85.118//test.php");
            // 建立http连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 设置允许输出
            conn.setDoOutput(true);

            conn.setDoInput(true);

            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            //转换为字节数组
            byte[] data = (obj.toString()).getBytes();
            // 设置文件长度
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));

            // 设置文件类型:
            conn.setRequestProperty("contentType", "application/json");


            // 开始连接请求
            conn.connect();
            OutputStream  out = conn.getOutputStream();     
            // 写入请求的字符串
            out.write((obj.toString()).getBytes());
            out.flush();
            out.close();

            System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (conn.getResponseCode() == 200) {
                System.out.println("连接成功");
                // 请求返回的数据
                InputStream in = conn.getInputStream();
                String a = null;
                try {
                    byte[] data1 = new byte[in.available()];
                    in.read(data1);
                    // 转成字符串
                    a = new String(data1);
                    System.out.println(a);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            } else {
                System.out.println("no++");
            }

        } catch (Exception e) {

        }

    }
}

服务端代码test.php

<?php
        $result = file_get_contents('php://input');
        echo $result;
        echo json_decode(json_encode($result));

?>

这里面的json_encode是对字符串进行json编码,json_decode是对字符串进行json解码

返回结果:
{“app_name”:[“全民大讨论”],”app_ip”:[“10.21.243.234”],”app_type”:[“001”],”app_port”:[8080],”app_area”:[“asd”]}
200
连接成功
{“app_name”:[“全民大讨论”],”app_ip”:[“10.21.243.234”],”app_type”:[“001”],”app_port”:[8080],”app_area”:[“asd”]}{“app_name”:[“全民大讨论”],”app_ip”:[“10.21.243.234”],”app_type”:[“001”],”app_port”:[8080],”app_area”:[“asd”]}

http协议详解,这篇文章讲的很好

  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
可以使用Java提供的HttpURLConnection或者Apache HttpClient库来实现POST请求提交JSON参数。 使用HttpURLConnection实现POST请求提交JSON参数的示例代码如下: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 添加请求头 con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); // 发送POST请求 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(json.getBytes("UTF-8")); os.flush(); os.close(); // 获取返回结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印返回结果 System.out.println(response.toString()); } } ``` 使用Apache HttpClient库实现POST请求提交JSON参数的示例代码如下: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); // 设置请求头 request.setHeader("Content-Type", "application/json"); // 设置请求参数 StringEntity params = new StringEntity(json); request.setEntity(params); // 发送POST请求 HttpResponse response = httpClient.execute(request); // 获取返回结果 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } // 打印返回结果 System.out.println(result.toString()); } } ``` 以上示例代码仅供参考,实际使用时需要根据自己的需求进行修改。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值