HttpClient实现JAVA项目之间请求

一、项目一(发送端)

/** 
     * post请求(用于key-value格式的参数) 
     * @author zyi
     * @param url 
     * @param params 
     * @return 
     */ 
	@SuppressWarnings({ "resource", "deprecation" })
	public static String httpClientPost(String url,Map params){
		System.out.println("-------->请求路径:"+url);
		BufferedReader in = null;    
        try {    
            // 定义HttpClient    
            HttpClient client = new DefaultHttpClient();    
            // 实例化HTTP方法    
            HttpPost request = new HttpPost();    
            request.setURI(new URI(url));  
              
            //设置参数  
            List nvps = new ArrayList();   
            for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {  
                String name = (String) iter.next();  
                String value = String.valueOf(params.get(name));  
                nvps.add(new BasicNameValuePair(name, value));                 
                System.out.println("-------->传递参数"+name +":"+value);  
            }           
            request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));  
            
            HttpResponse response = client.execute(request);    
            int code = response.getStatusLine().getStatusCode();  
            if(code == 200){//请求成功
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"utf-8"));  
                StringBuffer sb = new StringBuffer("");    
                String line = "";    
                String NL = System.getProperty("line.separator");//换行符,平台无关性
                while ((line = in.readLine()) != null) {    
                    sb.append(line + NL);    
                }                  
                in.close();                 
                return sb.toString();  
            }  
            else{
                System.out.println("请求失败,且状态码为:" + code);  
                return ""+code;  
            }  
        }  
        catch(Exception e){  
            e.printStackTrace();                
            return null;  
        }
	}

项目二(接收端)


你可能感兴趣的:(JAVA)