java发送POST请求请求数据为json格式

Posted 17mark

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java发送POST请求请求数据为json格式相关的知识,希望对你有一定的参考价值。

项目中遇到传json数据的接口,总结一下吧。再遇到就能更快的进行测试了。后续集成到自动化测试接口软件中。
json相关jar包下载
请求相关jar包下载

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

import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

public abstract class TestSend 

   // String URL = "url";

    public static void main(String[] args) 

        JSONObject jsobj1 = new JSONObject();
         jsobj1.put("key","value");
        
        
        //System.out.println(jsobj1);
        post(jsobj1,"url");//注册
    

    public static String post(JSONObject json,String URL) 

        HttpClient client = new DefaultHttpClient();
        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 = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\\n");
            inStream.close();

            result = strber.toString();
            System.out.println(result);
            
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
                
                    System.out.println("请求服务器成功,做相应处理");
                
             else 
                
                System.out.println("请求服务端失败");
                
            
            

         catch (Exception e) 
            System.out.println("请求异常");
            throw new RuntimeException(e);
        

        return result;
    


以上是关于java发送POST请求请求数据为json格式的主要内容,如果未能解决你的问题,请参考以下文章

使用axios发送post请求,将JSON数据改为为form类型

使用axios发送post请求,将JSON数据改为为form类型

requests: 发送一个json格式的post请求

RestTemplate发送数据为JSON的Post请求

HTTP POST 发送JSON格式数据(解决Expect:100-continue 问题)

如何向php服务器发送数据为json的post请求