java 发送http请求

使用jersey

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;

import net.sf.json.JSONObject;

import com.chinaUnicom.entitys.OrgObject;
import com.sun.jersey.core.util.MultivaluedMapImpl;

 

public class CommonClient {
	public static String restGet(String restUrl) throws Exception{
		Client client = ClientBuilder.newBuilder().build();
		Response response = client.target(restUrl).request().get();
		
		String result = null;
		if(Response.Status.OK.getStatusCode() ==response.getStatusInfo().getStatusCode()){
			 result =  response.readEntity(String.class);
		}else{
			System.out.println(response.getStatusInfo().getStatusCode());
			throw new Exception(String.format("%s call failed", restUrl));
		}
		 
		return result;
	}
	public static String restPost(String restUrl,MultivaluedMap<String, String> formData) throws Exception{
		Client client = ClientBuilder.newBuilder().build();
		Response response = client.target(restUrl).request().post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
		 
		
		String result = null;
		if(Response.Status.OK.getStatusCode() ==response.getStatusInfo().getStatusCode()){
			 result =  response.readEntity(String.class);
		}else{
			System.out.println(response.getStatusInfo().getStatusCode());
			throw new Exception(String.format("%s call failed", restUrl));
		}
		 
		return result;
	}
	 
	public static void main(String[] args) throws Exception {
//		MultivaluedMap par = new MultivaluedMapImpl();
//		par.add("lifeOrder", "CREATE_CTNR");
//		par.add("operationId", "121312");
//		par.add("containerConfigId", "1145");
//		par.add("statusType", "0");
//		String s = CommonClient.restPost("http://10.0.210.57:8080/ctnrDefCtrl/rest/containerLifeManage/sendContainerLifeOrder",par);
//		
		//String s = CommonClient.restGet("http://10.0.209.182:8000/Product/GetProducts");
//		String s = CommonClient.restGet("http://10.0.209.182:9000/App/GetApps/1");
//		System.out.println(s);
//		
//		System.out.println(s);
		//Sys/AddOrgInf
		
 		 String url = "http://10.0.209.182:9000/Sys/AddOrgInfo";
 
 		JSONObject json = JSONObject.fromObject(info);
 				MultivaluedMap par = new MultivaluedMapImpl();
				par.add("orgInfo", json.toString());
//				par.add("description", "description");
//				par.add("fax", "fax");
//				par.add("orgCode", "orgCode");
  
		System.out.println(String.format("请求路径及参数为%s", url));
		String s = CommonClient.restPost(url,par);
			 
			
		
		
	}

}

 

你可能感兴趣的:(java)