常用工具类

扫码查看

1.发送post请求,传输json数据

package net.shopxx.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import okhttp3.OkHttpClient;

public class HttpRequestUtil {

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

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = 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){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = JSON.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(response);
        return response;
    }

    public static void main(String[] args) {
        //String url="http://www.laotinghuagong.com/event/online";
        String url="http://localhost:8083/gdsk/event.do?online";
        //appid=190920753389&sign=82D51AB250C38800B70B2F82440464DB&imei=363620190803947
        //&msgId=dadf7a7fd3454e5facde2d450957a275&type=wifi&address=23423423234&time=2156633&lng=119.3255211&lat=39.552455
        JSONObject jsondata=new JSONObject();
        jsondata.put("appid", "190920753389");
        jsondata.put("sign", "82D51AB250C38800B70B2F82440464DB");
        jsondata.put("imei", "363620190803947");
        jsondata.put("msgId", "dadf7a7fd3454e5facde2d450957a275");
//        jsondata.put("type", "wifi");
//        jsondata.put("address", "23423423234");
//        jsondata.put("time", "2156633");
//        jsondata.put("lng", "119.3255211");
//        jsondata.put("lat", "39.552455");
        //
        JSONObject doPost = doPost(url, jsondata);
    }
}
01-08 10:23
查看更多