package com.huigou.uasp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;



public class RestUtil {
	//get
	  public String getMethod(String url) throws IOException {
	    URL restURL = new URL(url);
	 
	    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
	 
	    conn.setRequestMethod("GET"); // POST GET PUT DELETE
	    conn.setRequestProperty("Accept", "application/json");
	 
	    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	    String line,backStr="";
	    while((line = br.readLine()) != null ){
	    	backStr+=line;
	    //  System.out.println("返回："+line);
	    }
	    br.close();
	    return backStr;
	  }
	 
	  //post 
	  public String postMethod(String url, String query) throws IOException {
	    URL restURL = new URL(url);
	    String line,backStr="";
	    BufferedReader br = null;
	  try{	    
	    HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
	    conn.setRequestMethod("POST");
	    conn.setRequestProperty("Content-Type", "application/json");
	    conn.setDoOutput(true);

	    PrintStream ps = new PrintStream(conn.getOutputStream());
	    ps.print(query);
	    ps.close();
	 
	     br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	
	    while((line = br.readLine()) != null ){
	    	backStr+=line;
	     //  System.out.println("返回："+line);
	    }
	 System.out.println("res:=="+backStr);
	       br.close();
	   } catch (Exception e) {
		  backStr="Failure:"+e.getMessage();  
          e.printStackTrace();
       } finally{
    	   if (br!=null){
    		   br.close();
    	   }
       }
	    return backStr;
	  }
	 
	  public static void main(String[] args) {
	      RestUtil restUtil = new RestUtil();
	    try {
	    	String res=restUtil.getMethod("http://www.baidu.com");
	        System.out.println("res get==="+res);
	      String url = "";
	      String query = ""; //json格式
	      res=restUtil.postMethod(url, query);
	     System.out.println("res= post=="+res);
	 
	    }catch (Exception e){
	      System.out.println(e.getMessage());
	    }
	  }
	 
	}

	