精华内容
参与话题
问答
  • HttpUtil 请求工具类

    2018-07-24 17:04:29
    public class HttpUtil { private static Logger log = Logger.getLogger("wapshop_log"); private final static int CONNECT_TIMEOUT = 5000; // in milliseconds private final static String DEFA...
    public class HttpUtil {
    
        private static Logger log = Logger.getLogger("wapshop_log");
    
        private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
        private final static String DEFAULT_ENCODING = "UTF-8";
    
        public static String postData(String urlStr, String data) {
            return postData(urlStr, data, null);
        }
    
        public static String postData(String urlStr, String data, String contentType) {
            BufferedReader reader = null;
            OutputStreamWriter writer = null ;
            try {
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                conn.setConnectTimeout(CONNECT_TIMEOUT);
                conn.setReadTimeout(CONNECT_TIMEOUT);
                if (contentType != null)
                    conn.setRequestProperty("content-type", contentType);
                writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
                if (data == null) {
                    writer.write("");
                } else {
                    writer.write(data);
                }
                writer.flush();
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                    sb.append("\r\n");
                }
                return sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
                log.error(e);
            } finally {
                try {
                    if (reader != null){
                        reader.close();
                    }
                    if(writer != null){
                        writer.close();
                    }
                } catch (IOException e) {
                    log.error(e);
                }
            }
            return null;
        }
    
        public static String postHttp(String url, Map<String, String> map) {
            HttpClient httpclient = null;
            PostMethod post = null;
            SimpleHttpConnectionManager simpleHttpConnectionManager = null;
            String info = null;
            try {
                httpclient = new HttpClient();
                post = new PostMethod(url);
                // 设置编码方式
                post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
                httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
                httpclient.getHttpConnectionManager().getParams().setSoTimeout(30000);
                // 添加参数
                if (map != null) {
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        String key = entry.getKey();
                        post.addParameter(key, entry.getValue());
                    }
                }
                // 执行
                httpclient.executeMethod(post);
                // 接口返回信息
                info = new String(post.getResponseBody(), "UTF-8");
            } catch (Exception e) {
                log.error(e);
            } finally {
                // 关闭连接,释放资源
                if (post != null) {
                    post.releaseConnection();
                }
                if (httpclient != null) {
                    simpleHttpConnectionManager = ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager());
                    if (simpleHttpConnectionManager != null) {
                        simpleHttpConnectionManager.shutdown();
                    }
                }
    
            }
            return info;
        }
    
        /**
         * 处理get请求
         * 
         * @param url
         *            请求地址 如
         *            http://localhost:9090/base_rpc/basicData/getInvoice?t=1507513445960&invoiceId=039D906D07C74306B635DD89F87584CD&token=bd302857fbd4a01af7401fe229d43918
         * @return
         */
        public static String getHttp(String url) {
            HttpClient httpClient = null;
            GetMethod get = null;
            SimpleHttpConnectionManager simpleHttpConnectionManager = null;
            String info = null;
    
            try {
                httpClient = new HttpClient();
                get = new GetMethod(url);
                // 执行
                httpClient.executeMethod(get);
                // 接口返回信息
                info = new String(get.getResponseBody(), "UTF-8");
                log.info("接口【" + url + "】 返回:" + info);
            } catch (Exception e) {
                log.info("调用接口【" + url + "】  出错:" + e);
                return null;
            } finally {
                if (get != null) {
                    get.releaseConnection();
                }
                if (httpClient != null) {
                    simpleHttpConnectionManager = (SimpleHttpConnectionManager) httpClient.getHttpConnectionManager();
                    if (simpleHttpConnectionManager != null) {
                        simpleHttpConnectionManager.shutdown();
                    }
                }
            }
            return info;
        }
    
    }

     

    展开全文
  • HttpUtil工具类get与post请求

    万次阅读 2018-06-23 11:53:12
    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; ...impo...
    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.List;
    import java.util.Map;
    
    
    public class TestHttpUtil {
    	
    	public static void main(String[] args) {
            //发送 GET 请求
            String s=TestHttpUtil.sendGet("http://v.qq.com/x/cover/kvehb7okfxqstmc.html?vid=e01957zem6o", "");
            System.out.println(s);
    
    //        //发送 POST 请求
    //        String sr=HttpRequest.sendPost("http://www.toutiao.com/stream/widget/local_weather/data/?city=%E4%B8%8A%E6%B5%B7", "");
    //        JSONObject json = JSONObject.fromObject(sr);
    //        System.out.println(json.get("data"));
        }
    
        /**
         * 向指定URL发送GET方法的请求
         *
         * @param url
         *            发送请求的URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return URL 所代表远程资源的响应结果
         */
        public static String sendGet(String url, String param) {
            String result = "";
            BufferedReader in = null;
            try {
                String urlNameString = url + "?" + param;
                URL realUrl = new URL(urlNameString);
                // 打开和URL之间的连接
                URLConnection connection = realUrl.openConnection();
                // 设置通用的请求属性
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 建立实际的连接
                connection.connect();
                // 获取所有响应头字段
                Map<String, List<String>> map = connection.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    System.out.println(key + "--->" + map.get(key));
                }
                // 定义 BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送GET请求出现异常!" + e);
                e.printStackTrace();
            }
            // 使用finally块来关闭输入流
            finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * 向指定 URL 发送POST方法的请求
         *
         * @param url
         *            发送请求的 URL
         * @param param
         *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
         * @return 所代表远程资源的响应结果
         */
        public static String sendPost(String url, String param) {
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                URL realUrl = new URL(url);
                // 打开和URL之间的连接
                URLConnection conn = realUrl.openConnection();
                // 设置通用的请求属性
                conn.setRequestProperty("accept", "*/*");
                conn.setRequestProperty("connection", "Keep-Alive");
                conn.setRequestProperty("user-agent",
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(conn.getOutputStream());
                // 发送请求参数
                out.print(param);
                // flush输出流的缓冲
                out.flush();
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(
                        new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!"+e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally{
                try{
                    if(out!=null){
                        out.close();
                    }
                    if(in!=null){
                        in.close();
                    }
                }
                catch(IOException ex){
                    ex.printStackTrace();
                }
            }
            return result;
        }
    }
    

    展开全文
  • HttpUtil请求工具类

    万次阅读 2018-04-23 19:55:51
    public class HttpUtil { private static Logger log = Logger.getLogger(&quot;wapshop_log&quot;); private final static int CONNECT_TIMEOUT = 5000; // in milliseconds private fi...

    Http工具类post和get请求都有

    import com.aisino.global.context.common.logs.Logger;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.SimpleHttpConnectionManager;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Map;
    
    public class HttpUtil {
    
    	private static Logger log = Logger.getLogger("httputil_log");
    
    	private final static int CONNECT_TIMEOUT = 5000; // in milliseconds
    	private final static String DEFAULT_ENCODING = "UTF-8";
    
    	public static String postData(String urlStr, String data) {
    		return postData(urlStr, data, null);
    	}
    
    	public static String postData(String urlStr, String data, String contentType) {
    		BufferedReader reader = null;
    		try {
    			URL url = new URL(urlStr);
    			URLConnection conn = url.openConnection();
    			conn.setDoOutput(true);
    			conn.setConnectTimeout(CONNECT_TIMEOUT);
    			conn.setReadTimeout(CONNECT_TIMEOUT);
    			if (contentType != null)
    				conn.setRequestProperty("content-type", contentType);
    			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);
    			if (data == null) {
    				writer.write("");
    			} else {
    				writer.write(data);
    			}
    			writer.flush();
    			writer.close();
    
    			reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));
    			StringBuilder sb = new StringBuilder();
    			String line = null;
    			while ((line = reader.readLine()) != null) {
    				sb.append(line);
    				sb.append("\r\n");
    			}
    			return sb.toString();
    		} catch (IOException e) {
    			e.printStackTrace();
    			log.error(e);
    		} finally {
    			try {
    				if (reader != null)
    					reader.close();
    			} catch (IOException e) {
    				log.error(e);
    			}
    		}
    		return null;
    	}
    
    	public static String postHttp(String url, Map<String, String> map) {
    		HttpClient httpclient = null;
    		PostMethod post = null;
    		SimpleHttpConnectionManager simpleHttpConnectionManager = null;
    		String info = null;
    		try {
    			httpclient = new HttpClient();
    			post = new PostMethod(url);
    			// 设置编码方式
    			post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    			httpclient.getHttpConnectionManager().getParams().setSoTimeout(30000);
    			// 添加参数
    			if (map != null) {
    				for (Map.Entry<String, String> entry : map.entrySet()) {
    					String key = entry.getKey();
    					post.addParameter(key, entry.getValue());
    				}
    			}
    			// 执行
    			httpclient.executeMethod(post);
    			// 接口返回信息
    			info = new String(post.getResponseBody(), "UTF-8");
    		} catch (Exception e) {
    			log.error(e);
    		} finally {
    			// 关闭连接,释放资源
    			if (post != null) {
    				post.releaseConnection();
    			}
    			if (httpclient != null) {
    				simpleHttpConnectionManager = ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager());
    				if (simpleHttpConnectionManager != null) {
    					simpleHttpConnectionManager.shutdown();
    				}
    			}
    
    		}
    		return info;
    	}
    
    	/**
    	 * 处理get请求
    	 * 
    	 * @param url
    	 *            请求地址 如
    	 *            http://localhost:9090/base_rpc/basicData/getInvoice?t=1507513445960&invoiceId=039D906D07C74306B635DD89F87584CD&token=bd302857fbd4a01af7401fe229d43918
    	 * @return
    	 */
    	public static String getHttp(String url) {
    		HttpClient httpClient = null;
    		GetMethod get = null;
    		SimpleHttpConnectionManager simpleHttpConnectionManager = null;
    		String info = null;
    
    		try {
    			httpClient = new HttpClient();
    			get = new GetMethod(url);
    			// 执行
    			httpClient.executeMethod(get);
    			// 接口返回信息
    			info = new String(get.getResponseBody(), "UTF-8");
    			log.info("接口【" + url + "】 返回:" + info);
    		} catch (Exception e) {
    			log.info("调用接口【" + url + "】  出错:" + e);
    			return null;
    		} finally {
    			if (get != null) {
    				get.releaseConnection();
    			}
    			if (httpClient != null) {
    				simpleHttpConnectionManager = (SimpleHttpConnectionManager) httpClient.getHttpConnectionManager();
    				if (simpleHttpConnectionManager != null) {
    					simpleHttpConnectionManager.shutdown();
    				}
    			}
    		}
    		return info;
    	}
    
    }
    
    
    展开全文
  • Http请求工具类HttpUtil

    千次阅读 2015-04-07 15:17:58
    httpGet + hostname in certificate didn't match  报错! HTTPS加密引起的。 解决https需要验证问题 Hostname in certificate didn't match? HttpClient工具类 ... String strRequest=cdoRe...

     

    httpGet + hostname in certificate didn't match   报错!

    HTTPS加密引起的。

    解决https需要验证问题

    Hostname in certificate didn't match?

    HttpClient工具类

     

    两种方式:

    GET、SET



     

    try	
    		{
    			String strRequest=cdoRequest.toXML();
    			String strTransName = cdoRequest.getStringValue("strTransName");
    			String _strURL = strUrl + "?strTransName=" + strTransName + "&$$CDORequest$$=" + java.net.URLEncoder.encode(strRequest,"UTF-8");
    			if(_strURL.length()>=1024)
    			{
    				httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_POST);
    				Map<String,String> paramMap = new HashMap<String,String>();
    				paramMap.put("strTransName",cdoRequest.getStringValue("strTransName"));
    				paramMap.put("$$CDORequest$$",strRequest);
    				httpClient.setUrl(strUrl);
    				httpClient.setNameValuePair(paramMap);
    			}
    			else 
    			{
    				httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_GET);
    				httpClient.setUrl(_strURL);			
    			}
    			strCDOXml = httpClient.getResponseString();
    		}catch(Exception ex)
    		{
    			logger.error(ex.getMessage(), ex); 		
    			return Return.valueOf(-1," http Status:"+httpClient.getStatus()+";Send Http Request ERROR:"+ex.getMessage());	
    		} 

     

     

     

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.Map;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.log4j.Logger;
    
    public class HttpUtil {
    	private static final Logger logger = Logger.getLogger(HttpUtil.class);
    	/**
    	 * http post请求
    	 * @param url						地址
    	 * @param postContent				post内容格式为param1=value&param2=value2&param3=value3
    	 * @return
    	 * @throws IOException
    	 */
    	public static String httpPostRequest(URL url, String postContent) throws Exception{
    		OutputStream outputstream = null;
    		BufferedReader in = null;
    		try
    		{
    			URLConnection httpurlconnection = url.openConnection();
    			httpurlconnection.setConnectTimeout(10 * 1000);
    			httpurlconnection.setDoOutput(true);
    			httpurlconnection.setUseCaches(false);
    			OutputStreamWriter out = new OutputStreamWriter(httpurlconnection
    					.getOutputStream(), "UTF-8");
    			out.write(postContent);
    			out.flush();
    			
    			StringBuffer result = new StringBuffer();
    			in = new BufferedReader(new InputStreamReader(httpurlconnection
    					.getInputStream(),"UTF-8"));
    			String line;
    			while ((line = in.readLine()) != null)
    			{
    				result.append(line);
    			}
    			return result.toString();
    		}
    		catch(Exception ex){
    			logger.error("post请求异常:" + ex.getMessage());
    			throw new Exception("post请求异常:" + ex.getMessage());
    		}
    		finally
    		{
    			if (outputstream != null)
    			{
    				try
    				{
    					outputstream.close();
    				}
    				catch (IOException e)
    				{
    					outputstream = null;
    				}
    			}
    			if (in != null)
    			{
    				try
    				{
    					in.close();
    				}
    				catch (IOException e)
    				{
    					in = null;
    				}
    			}
    		}	
    	}	
    	
    	/**
    	 * 通过httpClient进行post提交
    	 * @param url				提交url地址
    	 * @param charset			字符集
    	 * @param keys				参数名
    	 * @param values			参数值
    	 * @return
    	 * @throws Exception
    	 */
    	public static String HttpClientPost(String url , String charset , String[] keys , String[] values) throws Exception{
    		HttpClient client = null;
    		PostMethod post = null;
    		String result = "";
    		int status = 200;
    		try {
    	           client = new HttpClient();                
                   //PostMethod对象用于存放地址
                 //总账户的测试方法
                   post = new PostMethod(url);         
                   //NameValuePair数组对象用于传入参数
                   post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);//在头文件中设置转码
    
                   String key = "";
                   String value = "";
                   NameValuePair temp = null;
                   NameValuePair[] params = new NameValuePair[keys.length];
                   for (int i = 0; i < keys.length; i++) {
                	   key = (String)keys[i];
                	   value = (String)values[i];
                	   temp = new NameValuePair(key , value);   
                	   params[i] = temp;
                	   temp = null;
                   }
                  post.setRequestBody(params); 
                   //执行的状态
                  status = client.executeMethod(post); 
                  logger.info("status = " + status);
                   
                  if(status == 200){
                	  result = post.getResponseBodyAsString();
                  }
                   
    		} catch (Exception ex) {
    			// TODO: handle exception
    			throw new Exception("通过httpClient进行post提交异常:" + ex.getMessage() + " status = " + status);
    		}
    		finally{
    			post.releaseConnection(); 
    		}
    		return result;
    	}
    	
    	/**
    	 * 字符串处理,如果输入字符串为null则返回"",否则返回本字符串去前后空格。
    	 * @param inputStr			输入字符串
    	 * @return	string 			输出字符串
    	 */
        public static String doString(String inputStr){
        	//如果为null返回""
            if(inputStr == null || "".equals(inputStr) || "null".equals(inputStr)){
        		return "";
        	}	
            //否则返回本字符串把前后空格去掉
        	return inputStr.trim();
        }
    
        /**
         * 对象处理,如果输入对象为null返回"",否则则返回本字符对象信息,去掉前后空格
         * @param object
         * @return
         */
        public static String doString(Object object){
        	//如果为null返回""
            if(object == null || "null".equals(object) || "".equals(object)){
        		return "";
        	}	
            //否则返回本字符串把前后空格去掉
        	return object.toString().trim();
        }
        
    }

     

    使用:

    String returnXML = HttpUtil.httpPostRequest(new URL(sendURL), postContent);

     

     工具类2:

    public class HttpUtil {
    	private static Log log = LogFactory.getLog(HttpUtil.class);
    
    	private static final String DEFAULT_HTTP_CHARSET = "UTF-8";
    	
    	private static final String GETID_URL = ProPertiesUtil.getValue("/server.properties", "getidurl");
    	
    	private static DefaultHttpClient httpClient = new DefaultHttpClient();
    
    	private HttpUtil() {}
    	
    	
    	public static String sendHttpByPost(String url,Map map) throws Exception{
    		HttpClient httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_POST);
    		/*Map<String,String> paramMap = new HashMap<String,String>();
    		paramMap.put("wf_type_id",wf_type_id.toString());
    		paramMap.put("customer_id",customer_id.toString());
    		paramMap.put("thirdparty_id",thirdparty_id.toString());
    		paramMap.put("order_no",order_no);
    		paramMap.put("order_idss",order_idss);
    		paramMap.put("user_id",user_id.toString());
    		paramMap.put("wf_code",wf_code);
    		paramMap.put("step",step.toString());
    		paramMap.put("wf_id", wf_id.toString());*/
    		
    		httpClient.setUrl(url);
    		httpClient.setNameValuePair(map);
    	
    		return  httpClient.getResponseString();
    		
    	}
    	
    	public static String httpGet(String url) {
    		String strReturn = "";
    		HttpUriRequest request = new HttpGet(url);
    		try {
    			HttpResponse response = httpClient.execute(request);
    			HttpEntity entity = response.getEntity();
    			strReturn = EntityUtils.toString(entity,DEFAULT_HTTP_CHARSET);
    		}catch(Exception e) {
    			// 网络异常
    			log.error(e.getMessage());
    		}
    		return strReturn;
    	}
    	
    	
    	public static void main(String[] args) throws JSONException, Exception{
    		
    		String strUrl1 = "http://localhost:8084/test/order/addOrder.do?orderCode=123456789&totalFee=39800";
    		System.out.println(httpGet(strUrl1));
    	}
    	
    }

     

    或:

    public String getMedia(String token,String mediaID){
    		logger.info("getMedia=============start");
    		String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+mediaID;
        	
        	BufferedInputStream bis = null;
        	FileOutputStream fos = null;
        	String imgFilePath = null;
    		try {
               HttpClient client = new DefaultHttpClient();  
               HttpGet httpGet = new HttpGet(url);  
               HttpResponse response = client.execute(httpGet); 
               HttpEntity entity = response.getEntity();  
               
               
               // 根据内容类型获取扩展名
               String fileExt = getFileEndWitsh(entity.getContentType().getValue());
               if(StringUtils.isEmpty(fileExt)) {
            	   logger.error("上传图片出错:content-Type" +entity.getContentType().getValue() + EntityUtils.toString(entity, "UTF-8"));
            	   return null;
               }
               String tmpImgPath = ProPertiesUtil.getValue("/auction.properties", "tmp_img_path");
               
       		   imgFilePath = getPhysicalPath(tmpImgPath) + File.separator + mediaID + fileExt;;// 新生成的图片
       		
               bis = new BufferedInputStream(entity.getContent());
               fos = new FileOutputStream(new File(imgFilePath));
               byte[] buf = new byte[8096];
               int size = 0;
               while ((size = bis.read(buf)) != -1)
                 fos.write(buf, 0, size);
               fos.close();
               bis.close();
    
               logger.info("下载媒体文件成功,filePath="+ imgFilePath);
             } catch (Exception e) {
            	 imgFilePath = null;
            	 logger.error("下载媒体文件失败:",e);
             } finally {
            	 if (bis != null) {
            		 try {
            			 bis.close();
            		 } catch (IOException e) {
            			 logger.error("连接微信出错:",e);
            		 }
            	}
            	if (fos != null) {
            	     try {
            	    	 fos.close();
            	     } catch (IOException e) {
            	    	 logger.error("连接微信出错:",e);
            	     }
            	}
            }
    		return imgFilePath;
        }

     

    HttpClient httpclient = new DefaultHttpClient();
    		HttpPost post = new HttpPost(IMAGE_FTP_PATH);
    		File file = new File(filePath);
    		FileBody fileBody = new FileBody(file);
    		try {
    
    			MultipartEntity entity = new MultipartEntity();
    			entity.addPart("file", fileBody);
    			post.setEntity(entity);
    			HttpResponse response = httpclient.execute(post);
    			logger.info("图片服务器返回code:" + response.getStatusLine().getStatusCode());
    			if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    
    				HttpEntity entitys = response.getEntity();
    				if (entitys != null) {
    					//resultLen = entity.getContentLength();
    					returnStr = EntityUtils.toString(entitys);
    					
    					logger.info("图片服务器返回returnStr:" + returnStr);
    				}
    			}
    			httpclient.getConnectionManager().shutdown();
    			
    			//删除本地
    			//file.delete();
    		} catch (UnsupportedEncodingException e) {
    			logger.error(e.getMessage(), e);
    		} catch (ClientProtocolException e) {
    			logger.error(e.getMessage(), e);
    		} catch (IOException e) {
    			logger.error(e.getMessage(), e);
    		}

     

     

    3、

     

     

    package com.common.util;
    
    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.net.URLEncoder;
    import java.util.Map;
    
    /** 
     * @author Administrator 
     * 
     */
    public class HttpUtils {
    
    	/** 
    	 * 使用Get方式获取数据 
    	 *  
    	 * @param url 
    	 *            URL包括参数,http://HOST/XX?XX=XX&XXX=XXX 
    	 * @param charset 
    	 * @return 
    	 */
    	public static String sendGet(String url) {
    		String result = "";
    		BufferedReader in = null;
    		try {
    			URL realUrl = new URL(url);
    			// 打开和URL之间的连接  
    			URLConnection connection = realUrl.openConnection();
    			// 设置通用的请求属性  
    			connection.setRequestProperty("accept", "*/*");
    			connection.setRequestProperty("connection", "Keep-Alive");
    			connection.setRequestProperty("user-agent",
    					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    			// 建立实际的连接  
    			connection.connect();
    			// 定义 BufferedReader输入流来读取URL的响应  
    			in = new BufferedReader(new InputStreamReader(connection
    					.getInputStream(), "utf-8"));
    			String line;
    			while ((line = in.readLine()) != null) {
    				result += line;
    			}
    		} catch (Exception e) {
    			System.out.println("发送GET请求出现异常!" + e);
    			e.printStackTrace();
    		}
    		// 使用finally块来关闭输入流  
    		finally {
    			try {
    				if (in != null) {
    					in.close();
    				}
    			} catch (Exception e2) {
    				e2.printStackTrace();
    			}
    		}
    		return result;
    	}
    
    	/**  
    	 * POST请求,字符串形式数据  
    	 * @param url 请求地址  
    	 * @param param 请求数据  
    	 * @param charset 编码方式  
    	 */
    	public static String sendPostUrl(String url, String param, String charset) {
    
    		PrintWriter out = null;
    		BufferedReader in = null;
    		String result = "";
    		try {
    			URL realUrl = new URL(url);
    			// 打开和URL之间的连接  
    			URLConnection conn = realUrl.openConnection();
    			// 设置通用的请求属性  
    			conn.setRequestProperty("accept", "*/*");
    			conn.setRequestProperty("connection", "Keep-Alive");
    			conn.setRequestProperty("user-agent",
    					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    			// 发送POST请求必须设置如下两行  
    			conn.setDoOutput(true);
    			conn.setDoInput(true);
    			// 获取URLConnection对象对应的输出流  
    			out = new PrintWriter(conn.getOutputStream());
    			// 发送请求参数  
    			out.print(param);
    			// flush输出流的缓冲  
    			out.flush();
    			// 定义BufferedReader输入流来读取URL的响应  
    			in = new BufferedReader(new InputStreamReader(
    					conn.getInputStream(), charset));
    			String line;
    			while ((line = in.readLine()) != null) {
    				result += line;
    			}
    		} catch (Exception e) {
    			System.out.println("发送 POST 请求出现异常!" + e);
    			e.printStackTrace();
    		}
    		// 使用finally块来关闭输出流、输入流  
    		finally {
    			try {
    				if (out != null) {
    					out.close();
    				}
    				if (in != null) {
    					in.close();
    				}
    			} catch (IOException ex) {
    				ex.printStackTrace();
    			}
    		}
    		return result;
    	}
    
    	/**  
    	 * POST请求,Map形式数据  
    	 * @param url 请求地址  
    	 * @param param 请求数据  
    	 * @param charset 编码方式  
    	 */
    	public static String sendPost(String url, Map<String, String> param,
    			String charset) {
    
    		StringBuffer buffer = new StringBuffer();
    		if (param != null && !param.isEmpty()) {
    			for (Map.Entry<String, String> entry : param.entrySet()) {
    				buffer.append(entry.getKey()).append("=").append(
    						URLEncoder.encode(entry.getValue())).append("&");
    
    			}
    		}
    		buffer.deleteCharAt(buffer.length() - 1);
    
    		PrintWriter out = null;
    		BufferedReader in = null;
    		String result = "";
    		try {
    			URL realUrl = new URL(url);
    			// 打开和URL之间的连接  
    			URLConnection conn = realUrl.openConnection();
    			// 设置通用的请求属性  
    			conn.setRequestProperty("accept", "*/*");
    			conn.setRequestProperty("connection", "Keep-Alive");
    			conn.setRequestProperty("user-agent",
    					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    			// 发送POST请求必须设置如下两行  
    			conn.setDoOutput(true);
    			conn.setDoInput(true);
    			// 获取URLConnection对象对应的输出流  
    			out = new PrintWriter(conn.getOutputStream());
    			// 发送请求参数  
    			out.print(buffer);
    			// flush输出流的缓冲  
    			out.flush();
    			// 定义BufferedReader输入流来读取URL的响应  
    			in = new BufferedReader(new InputStreamReader(
    					conn.getInputStream(), charset));
    			String line;
    			while ((line = in.readLine()) != null) {
    				result += line;
    			}
    		} catch (Exception e) {
    			System.out.println("发送 POST 请求出现异常!" + e);
    			e.printStackTrace();
    		}
    		// 使用finally块来关闭输出流、输入流  
    		finally {
    			try {
    				if (out != null) {
    					out.close();
    				}
    				if (in != null) {
    					in.close();
    				}
    			} catch (IOException ex) {
    				ex.printStackTrace();
    			}
    		}
    		return result;
    	}
    
    	public static void main(String[] args) {
    	}
    }

     

     

    展开全文
  • HttpUtil工具类

    千次阅读 2019-07-15 16:40:51
    代码: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream;...import java.net.HttpURLConnection;...import java.net....
  • java:util:HttpUtil

    2020-04-28 18:05:28
    import com.alibaba.fastjson.JSON; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.*; import org.apache.......
  • HttpUtil工具

    2020-04-07 22:11:45
    1.发送get请求 String url = "http://www.sogou.com"; Map<String, Object> paramMap = new HashMap<>(); paramMap.put("query", 10086); // 无参GET请求 String result = Ht...
  • 封装的HttpUtil工具类

    2019-07-14 12:04:21
    因为我们在一个程序中要多次使用网络请求,所以需要...public class HttpUtil { public static void sendHttpRequest(final String address, final HttpCallbackListener listener){ new Thread(new Runnable() { ...
  • httpUtil

    2019-05-05 22:48:59
    网络请求工具类
  • HttpUtil工具类

    2017-12-05 12:04:40
    HttpClient远程调用工具类 get 和post 调用用访问别的系统接口 用http方式请求,包括调用时用的工具类
  • 一个拿来即用的httputil工具类

    千次阅读 2019-05-31 14:55:35
    工作中难免会用httpclien进行数据的跨系统传输,这几天老在用,调别的系统的接口,今天就给大家分享出来我用的工具类吧,主要是后期我用的时候可以找到。 package com.cnlive.shenhe.utils; ... ...import org.apac...
  • HttpUtil

    2013-01-18 17:37:45
    package forrest.cartoon.utils; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry;...import org.
  • httpUtil

    2018-10-17 15:11:00
    一、 import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.URISyntaxException;import java.nio.charset.Charset;import java.security.KeyManagementExc...
  • HttpUtil

    2015-09-17 10:01:03
    把项目中的httpUtil记录下来,方便以后查询或使用. public class MyHttpUtils { private static final int CONNECTION_TIMEOUT = 10000; private static final int READ_TIMEOUT = 10000; private static final ...
  • HttpUtil

    2020-11-03 11:47:25
    @Override public boolean saveTrsWenduData(TrsWenduReqVo trsWenduReqVo) { Map<String,String> params=new HashMap<>(2); params.put("fgs",trsWenduReqVo.getFgs()); params.put("access",...
  • httpUtil

    2020-08-18 23:26:44
    /** * post请求(用于请求json格式的参数) * @param url * @param params * @return */ public static String doPost(String url, String params) throws Exception { CloseableHttpClient httpclient = ...
  • HttpUtil

    千次阅读 2011-06-01 14:32:00
    package HttpUtil; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache....
  • HttpUtil

    2016-07-07 06:47:40
    public class HttpUtil { private const string sContentType = "application/x-www-form-urlencoded"; private const string sUserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.
  • HttpUtil

    2018-11-06 17:01:44
    package com.hlg.xboot.utils; import com.alibaba.fastjson.JSON; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache....
  • HttpUtil

    2017-03-27 18:13:55
    import android.util.Log; import org.json.JSONObject; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader;...import java.io.OutputSt

空空如也

1 2 3 4 5 ... 20
收藏数 9,107
精华内容 3,642
关键字:

httputil