通过java发送post请求参数为json格式

注:转载文章,当时为了做这个,费了好久时间没有解决,这个是唯一一个有用的,复制备下次

ava模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求。我使用的是第二种方法,下面是具体代码。

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * http请求工具
 */
public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    
    /**
     * 发送post请求
     * @param json
     * @param URL
     * @return
     */
    public static String sendPost(JSONObject json,String URL) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        post.addHeader("Authorization", "Basic YWRtaW46");
        String result;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            // 获取响应输入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功,做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
        } catch (Exception e) {
            logger.error("请求异常:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return result;
    }
}

调用方法

    public static void main(String[] args) {
        JSONObject EventTraceInput =new JSONObject();
        EventTraceInput.put("AreaCode","520181");
        EventTraceInput.put("TaskCode", "0");
        EventTraceInput.put("Opinion","test");
        JSONArray EventFile=new JSONArray();
        JSONObject file1 = new JSONObject();
        file1.put("TaskCode", 0);
        file1.put("FileState",0);
        file1.put("FileType",0);
        file1.put("FileName","1.jpg");
        file1.put("FileUrl","");
        file1.put("FileBase64","");
        EventFile.add(file1);
        EventTraceInput.put("EventFiles",EventFile);
        String url="***";
        System.out.println(sendPost(EventTraceInput,url));
    }

测试通过

你可能感兴趣的:(通过java发送post请求参数为json格式)