精华内容
下载资源
问答
  • public classPostUtil {/*** 发送post请求 *@paramurl 请求地址 *@paramjson json格式字符串 *@paramcontentType 这里用 "application/json" *@return */ public staticString post(String url, String json, String...

    importorg.apache.commons.lang.StringUtils;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.StatusLine;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.http.client.HttpResponseException;importorg.apache.http.client.ResponseHandler;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.conn.ssl.SSLConnectionSocketFactory;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.util.EntityUtils;importjavax.net.ssl.SSLContext;importjavax.net.ssl.TrustManager;importjavax.net.ssl.X509TrustManager;importjava.io.IOException;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;public classPostUtil {/*** 发送post请求

    *@paramurl 请求地址

    *@paramjson json格式字符串

    *@paramcontentType 这里用 "application/json"

    *@return

    */

    public staticString post(String url, String json, String contentType) {

    HttpClientBuilder httpClientBuilder=HttpClientBuilder.create();//HttpClient

    CloseableHttpClient client =httpClientBuilder.build();

    client=(CloseableHttpClient) wrapClient(client);

    HttpPost post= newHttpPost(url);try{

    StringEntity s= new StringEntity(json, "utf-8");if(StringUtils.isBlank(contentType)) {

    s.setContentType("application/json");

    }

    s.setContentType(contentType);

    post.setEntity(s);

    HttpResponse res=client.execute(post);

    HttpEntity entity=res.getEntity();

    String str= EntityUtils.toString(entity, "utf-8");returnstr;

    }catch(Exception e) {

    e.printStackTrace();

    }return null;

    }private staticorg.apache.http.client.HttpClient wrapClient(HttpClient base) {try{

    SSLContext ctx= SSLContext.getInstance("TLSv1");

    X509TrustManager tm= newX509TrustManager() {public voidcheckClientTrusted(X509Certificate[] xcs,

    String string)throwsCertificateException {

    }public voidcheckServerTrusted(X509Certificate[] xcs,

    String string)throwsCertificateException {

    }publicX509Certificate[] getAcceptedIssuers() {return null;

    }

    };

    ctx.init(null, new TrustManager[]{tm}, null);

    SSLConnectionSocketFactory sslsf= new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,

    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    CloseableHttpClient httpclient=HttpClients.custom().setSSLSocketFactory(sslsf).build();returnhttpclient;

    }catch(Exception ex) {return null;

    }

    }public class CharsetHandler implements ResponseHandler{privateString charset;publicCharsetHandler(String charset) {this.charset =charset;

    }publicString handleResponse(HttpResponse response)throwsClientProtocolException, IOException {

    StatusLine statusLine=response.getStatusLine();if (statusLine.getStatusCode() >= 300) {throw newHttpResponseException(statusLine.getStatusCode(),

    statusLine.getReasonPhrase());

    }

    HttpEntity entity=response.getEntity();if (entity != null) {if (!StringUtils.isBlank(charset)) {returnEntityUtils.toString(entity, charset);

    }else{returnEntityUtils.toString(entity);

    }

    }else{return null;

    }

    }

    }

    }

    展开全文
  • 项目中遇到传json数据的接口,总结一下...json相关jar包下载请求相关jar包下载import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import net.sf.json.JSONObject;import...

    项目中遇到传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;

    }

    }

    积极迎接各种挑战,才会使自己更加强大。

    展开全文
  • * 发送post请求 * @param url 路径 * @param jsonObject 参数(json类型) * @param encoding 编码格式 * @return * @throws ParseException * @throws IOException */ public static String send(String url...
    /**
         * 发送post请求
         * @param url  路径
         * @param jsonObject  参数(json类型)
         * @param encoding 编码格式
         * @return
         * @throws ParseException
         * @throws IOException
         */
        public static String send(String url, JSONObject jsonObject,String encoding) throws ParseException, IOException{
            String body = "";
     
            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            //创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
     
            //装填参数
            StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            //设置参数到请求对象中
            httpPost.setEntity(s);
            System.out.println("请求地址:"+url);
    //        System.out.println("请求参数:"+nvps.toString());
     
            //设置header信息
            //指定报文头【Content-type】、【User-Agent】
    //        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
     
            //执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
            return body;
        }
    

     

    展开全文
  • import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache....
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import org.apache.http.HttpResponse;
    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.util.EntityUtils;
    
    
    
    
    //定义发送数据
    JSONObject param = new JSONObject();
    param.put("username", "zhangshan");
    param.put("age", "18");
    //定义接收数据
    JSONObject result = new JSONObject();
    
    String url = "http://www.baidu.com";
    HttpPost httpPost = new HttpPost(url);
    CloseableHttpClient client = HttpClients.createDefault();
    //请求参数转JOSN字符串
    StringEntity entity = new StringEntity(param.toString(), "UTF-8");
    entity.setContentEncoding("UTF-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    try {
    	HttpResponse response = client.execute(httpPost);
    	if (response.getStatusLine().getStatusCode() == 200) {
    		result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
    	}
    } catch (IOException e) {
    	e.printStackTrace();
    	result.put("error", "连接错误!");
    }

    所需要的maven 、jar包

    <dependency>
    		<groupId>com.alibaba</groupId>
    	<artifactId>fastjson</artifactId>
    	<version>1.2.78</version>
    </dependency>
    <dependency>
    	<groupId>org.apache.httpcomponents</groupId>
    	<artifactId>httpclient</artifactId>
    	<version>4.5.13</version>
    </dependency>

    fastjson-1.2.78.jaricon-default.png?t=LA92https://repo1.maven.org/maven2/com/alibaba/fastjson/1.2.78/fastjson-1.2.78.jarhttpclient-4.5.13.jaricon-default.png?t=LA92https://repo1.maven.org/maven2/org/apache/httpcomponents/httpclient/4.5.13/httpclient-4.5.13.jar

    展开全文
  • java 通过发送json,post请求,返回json数据的方法发布于 2020-3-20|复制链接下面小妖就为大家分享一篇java 通过发送json,post请求,返回json数据的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小妖过来看...
  • java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求,方法一:package main.utils;import java.io.*;import java.net.HttpURLConnection;...
  • public ... }/*** 发送 post请求(带文件) * *@paramhttpUrl * 地址 *@parammaps * 参数 *@paramfileLists * 附件*/ public String sendHttpPost(String httpUrl, Map maps, ListfileLists) { HttpPost ...
  • 1.请参数是json格式 首先导入pom <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> <...
  • 直接上代码:http工具类:public static String httpPostWithjson(String url, String json) throws IOException {String result = "";HttpPost httpPost = new HttpPost(url);CloseableHttpClient httpClient = ...
  • 已封装工具类package ...import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org...
  • import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.H...
  • public staticString upload(String url){try{HttpClient httpclient= newDefaultHttpClient...HttpPost httppost= newHttpPost(url);MultipartEntity reqEntity= newMultipartEntity();ArrayList> enclosureList...
  • /*** 发送post请求* @param url 路径* @param jsonObject 参数(json类型)* @param encoding 编码格式* @return* @throws ParseException* @throws IOException*/public static String send(String url, JSONObject ...
  • /*** 发送post请求* @param url 路径* @param jsonObject 参数(json类型)* @param encoding 编码格式* @return* @throws ParseException* @throws IOException*/public static String send(String url, JSONObject ...
  • public static String sendPostReq(String url, JSONObject jsonObject) throws ParseException, IOException{ ... * 发送post请求 * @param url 路径 * @param jsonObject 参数(json类型) * @p...
  • 拿到需求我就开始修改原有的新添加使用户接口,在新添加使用户成功后,添加代码发送请求给第三方系统同步使用户信息。下面将详细讲解步骤。后端发送http请求需要的代码环境 需要两个jar包,httpclient 和 httpcore。...
  • import com.alibaba.fastjson.JSONObject;import org.apache....import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.a...
  • //模拟浏览器发送http请求完成固定地址的请求 public class HttpClientUtils { /** * 发送post请求 * @param url * @param json * @return */ public static JSONObject DO_POST(String url, ...
  • import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;import java.util...
  • java后台发送post请求 MultipartFile、json

    千次阅读 2020-12-23 16:41:12
    1、需求:建立邮件发送中间建,转发邮件,以此跳过网闸。...2、java post请求 public static Long sendGxMail(EmailRecords emailRecords,List<MultipartFile> uploadFiles) { try { String key = "...
  • PostMan发送请求 有两种方式: 已流的方式接收请求参数 // request为HttpServletRequest对象 BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8")...
  • java模拟post请求发送json,用两种方式实现,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求。方法一:public staticString sendPost(String url_param, String param) {String result...
  • 我开发了一个java代码,使用URL和...卷曲是:curl -i 'http://url.com' -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d '{"auth": { "passwordCredentials": {"user...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 138,394
精华内容 55,357
关键字:

java发送post请求返回json

java 订阅