爱玺玺

爱玺玺的生活日记本。wx:lb87626

java post json数据到服务器,这里模拟给大众发送

package test;


import com.alibaba.fastjson.JSONObject;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ContentType;

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 java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.HttpURLConnection;

import java.net.URL;



public class HttpRequest2 {


      public static String sendPost(String url,String param){

          OutputStreamWriter out =null;

          BufferedReader reader = null;

          String response = "";


          //创建连接

          try {

              URL httpUrl = null; //HTTP URL类 用这个类来创建连接

              //创建URL

              httpUrl = new URL(url);

              //建立连接

              HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();

              conn.setRequestMethod("POST");

              conn.setRequestProperty("Content-Type", "application/json");

              conn.setRequestProperty("connection", "keep-alive");

              conn.setRequestProperty("cookie", "_lxsdk_cuid=16e867e2917c8-04ee70b1f47369-454c092b-1fa400-16e867e2917c8; _lxsdk=16e867e2917c8-04ee70b1f47369-454c092b-1fa400-16e867e2917c8; _hc.v=9e1b90ca-ed1b-350f-55cd-94c07e2f1ecf.1574214446; edper=A9qKnOYond35KZJyHF1As0htSiFaxA6JPZ9ruXbnwHKK4_RxUpW69zYzvkM-2rTHNFWpjAj2UAHMg9826fQmrA; mpmerchant_portal_shopid=129383121; platformSource=1; userPlatform=PC; requestSource=dp; realAccountId=54187346; accountSource=0; accountId=73686054; __guid=87795908.4416902347484563000.1574216705117.926; monitor_count=2; _lxsdk_s=16e8845b632-0db-bc0-8fe%7Cuser-id%7C28");

              conn.setUseCaches(false);//设置不要缓存

              conn.setInstanceFollowRedirects(true);

              conn.setDoOutput(true);

              conn.setDoInput(true);

              conn.connect();

              //POST请求

              out = new OutputStreamWriter(

                      conn.getOutputStream());

              out.write(param);

              out.flush();

              //读取响应

              reader = new BufferedReader(new InputStreamReader(

                      conn.getInputStream()));

              String lines;

              while ((lines = reader.readLine()) != null) {

                  lines = new String(lines.getBytes(), "utf-8");

                  response+=lines;

              }

              reader.close();

              // 断开连接

              conn.disconnect();


          } catch (Exception e) {

              System.out.println("发送 POST 请求出现异常!"+e);

              e.printStackTrace();

          }

          //使用finally块来关闭输出流、输入流

          finally{

              try{

                  if(out!=null){

                      out.close();

                  }

                  if(reader!=null){

                      reader.close();

                  }

              }

              catch(IOException ex){

                  ex.printStackTrace();

              }

          }


          return response;

      }


/*

    public static String sendPost2(String url, String data) {

        String response = null;


        try {

        //CloseableHttpClient应该类似HttpClient之类的请求连接

            CloseableHttpClient httpclient = null;

            //CloseableHttpResponse获得请求的响应

            CloseableHttpResponse httpresponse = null;

            try {

                httpclient = HttpClients.createDefault();

                //HttpPost就是模拟浏览器的post提交,忘了,好像以前servernet里面用过

                HttpPost httppost = new HttpPost(url);

                httppost.setHeader("Cookie", "_lxsdk_cuid=16e867e2917c8-04ee70b1f47369-454c092b-1fa400-16e867e2917c8; _lxsdk=16e867e2917c8-04ee70b1f47369-454c092b-1fa400-16e867e2917c8; _hc.v=9e1b90ca-ed1b-350f-55cd-94c07e2f1ecf.1574214446; edper=A9qKnOYond35KZJyHF1As0htSiFaxA6JPZ9ruXbnwHKK4_RxUpW69zYzvkM-2rTHNFWpjAj2UAHMg9826fQmrA; mpmerchant_portal_shopid=129383121; platformSource=1; userPlatform=PC; requestSource=dp; realAccountId=54187346; accountSource=0; accountId=73686054; __guid=87795908.4416902347484563000.1574216705117.926; monitor_count=2; _lxsdk_s=16e877a999d-9cd-9f5-d7c%7Cuser-id%7C18");

                //处理字符串json数据为StringEntity

                StringEntity stringentity = new StringEntity(data,

                        ContentType.create("text/json", "UTF-8"));

                //httpost设置entity实体

                httppost.setEntity(stringentity);

                

                //httpclient客户端执行httppost发送

                httpresponse = httpclient.execute(httppost);

                //获取服务器返回的数据

                response = EntityUtils.toString(httpresponse.getEntity());


            } finally {

                if (httpclient != null) {

                    httpclient.close();

                }

                if (httpresponse != null) {

                    httpresponse.close();

                }

            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return response;

    }

*/

    public static void main(String[] args) {

    //用alibaba的fastjson定义一个jsonObject对象 jsonObject

        JSONObject jsonParam = new JSONObject();

        //在jsonParm对象中放入nam信息

        jsonParam.put("shopId", "s129383121");

        jsonParam.put("userId", "u1368044176");

        jsonParam.put("message", "发送成功66666666");

        jsonParam.put("type", 0);

        jsonParam.put("clientType", "100900");

        //将jsonParm转为json字符串

        String param = jsonParam.toJSONString();

        

        

        String url="https://m.dianping.com/general/platform/dzim/json/shop/forward1";

        //这里是发送过去的

        String sendPost = sendPost(url, param);

        System.out.println(sendPost);


    }


}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5