java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

Java post Json 格式数据

Java的HashMap 可以方便的转换成json,如果将json传给php,php可以方便的转换成array,json就这样充当了数据传输的角色,当的不错。

package com.javaer.test;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;
import java.util.HashMap;

public class JSONTtest {


    public static void main(String[] args) throws JSONException {
        JSONObject jsondata=new JSONObject();
        jsondata.put("id","23");
        jsondata.put("name","Tom");
        postJson("http://localhost/DEMO/JsonRead/read.php?act=post",jsondata);
    }

    public static String postJson(String url, JSONObject json){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        String result=null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                 result = EntityUtils.toString(res.getEntity());// 返回json格式:

               // response = JSONObject.stringToValue(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(result);
        return result;
    }


}

接受的php端

控制台返回了php收到了java传过来json 进行转换成数组

Hipoststring(24) "{"name":"Tom","id":"23"}"
array(2) {
  ["name"]=>
  string(3) "Tom"
  ["id"]=>
  string(2) "23"
}


This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-post-json-data/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply