java发送post请求

一、依赖


    org.apache.httpcomponents
    httpclient
    4.2.5






    org.apache.httpcomponents
    httpcore
    4.2.5





    net.sf.json-lib
    json-lib
    2.2
    jdk15

二、准备一些随机的json格式的body,用做post请求传入的数据

随机生成数字和字母的组合:https://blog.csdn.net/yaodong_y/article/details/8115250

java用JSONObject处理json数据: https://www.cnblogs.com/jiayongji/p/6417862.html


三、java代码

package gyd.com.test;


import org.apache.http.Header;
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.params.CoreConnectionPNames;
//import java.util.UUID;
import net.sf.json.JSONObject;
import java.nio.charset.Charset;
import java.util.Random;  

public class postSend {
	public static boolean httpPostWithJson(JSONObject jsonObj,String url){
	    boolean isSuccess = false;
	    
	    HttpPost post = null;
	    try {
	        HttpClient httpClient = new DefaultHttpClient();
	        // 设置超时时间
	        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 2000);
	        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 2000);
	        //传入url
	        post = new HttpPost(url);
	        // 设置Header
	        post.setHeader("Content-type", "application/json; charset=utf-8");
	        post.setHeader("Connection", "keep-alive");
//	        String sessionId = getSessionId();
	        post.setHeader("Cookie", "JSESSIONID=AB0BADA65DD4F58ABA4FABDA3793C042");
//	        post.setHeader("appid", appId);
	                    
	        // 构建消息实体(body)
	        StringEntity entity = new StringEntity(jsonObj.toString(), Charset.forName("UTF-8"));
	        entity.setContentEncoding("UTF-8");
	        // 发送Json格式的数据请求
	        entity.setContentType("application/json");
	        post.setEntity(entity);
	        
	        //获取post返回结果
	        HttpResponse response = httpClient.execute(post);
	            
	        // 检验返回码
	        int statusCode = response.getStatusLine().getStatusCode();
	        if(statusCode != HttpStatus.SC_OK){
	            System.out.println("请求出错: "+statusCode);
	            isSuccess = false;
	        }else{
	            int retCode = 0;
//	            String sessendId = "";
	            // 返回码中包含retCode及会话Id
	            for(Header header : response.getAllHeaders()){
	                if(header.getName().equals("retcode")){
	                    retCode = Integer.parseInt(header.getValue());
	                }
//	                if(header.getName().equals("SessionId")){
////	                    sessendId = header.getValue();
//	                }
	            }
	            
	            if(200 != retCode ){
	                // 日志打印
	                System.out.println("error return code,  sessionId: "+"retCode: "+retCode);
	                isSuccess = false;
	            }else{
	                isSuccess = true;
	            }
	        }
	        System.out.println(response);
	    } catch (Exception e) {
	        e.printStackTrace();
	        isSuccess = false;
	    }finally{
	        if(post != null){
	            try {
	                post.releaseConnection();
	                Thread.sleep(500);
	            } catch (InterruptedException e) {
	                e.printStackTrace();
	            }
	        }
	    }
	    
	    return isSuccess;
	}

	

	  
	public static class StringRandom {  
	  
	    //生成随机数字和字母
	    private String getStringRandom(int length) {  
	          
	        String val = "";  
	        Random random = new Random();  
	          
	        //参数length,表示生成几位随机数  
	        for(int i = 0; i < length; i++) {  
	              
	            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";  
	            //输出字母还是数字  
	            if( "char".equalsIgnoreCase(charOrNum) ) {  
	                //输出是大写字母还是小写字母  
	                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;  
	                val += (char)(random.nextInt(26) + temp);  
	            } else if( "num".equalsIgnoreCase(charOrNum) ) {  
	                val += String.valueOf(random.nextInt(10));  
	            }  
	        }
	        return val;  
	    }
	    
	    //随机生成消息实体(body)
	    public JSONObject myAdd() {
	        String JSON_SIMPLE = "{\"resourcename\":\""+getStringRandom(5)+"\",\"resourceid\":\""+getStringRandom(6)+"\",\"applyuserid\":\"1\"}";
	        JSONObject obj = JSONObject.fromObject(JSON_SIMPLE);
	        return obj;
	    }
	} 
	      
	    public static void  main(String[] args) {  
	    	
	        StringRandom test = new StringRandom();  
	        //发送十次post请求
	        for (int i=0; i<10;i++) {
	        	//这里是随机生成的body
	        	JSONObject myBody = test.myAdd();
	        	//这里是你的url
	        	String myurl = "http://localhost:18080/ywsjglprj/apply/add";
	        	//header在里面设置
	        	httpPostWithJson(myBody,myurl);
	        	try{
	        		Thread.sleep(1000);
	        		}catch(Exception e){
	        		System.exit(0);//退出程序
	        		}
	        }
	        //测试  
 
	    }  
	 
//	public static  String JSON_SIMPLE = "{'name':'tom','age':16}";
    
	// 构建唯一会话Id
//	public static String getSessionId(){
//	    UUID uuid = UUID.randomUUID();
//	    String str = uuid.toString();
//	    return str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23) + str.substring(24);
//	}
}





你可能感兴趣的:(java,http请求)