java 之程序中的http请求

背景

  java程序中有时需要我们发起http级别的请求,例如抓数据或者第三方对接时,一般分为两种:一种是只需我们发起请求,还有一种是我们不但要发起请求,还要拿到请求后的数据来进行下一步处理

实现

  针对以上两种情况我们来给出简单的实现,对于在技术实现上一般分为两类:通过HttpClient方式和通过流的形式:

  • 只发送get请求
    • 通过httpclient方式 
public static String httpGet(String url, String charset)
   throws HttpException, IOException {
  String json = null;
  HttpGet httpGet = new HttpGet();
  // 设置参数
  try {
   httpGet.setURI(new URI(url));
  } catch (URISyntaxException e) {
   throw new HttpException("请求url格式错误。"+e.getMessage());
  }
  // 发送请求
  HttpResponse httpResponse = client.execute(httpGet);
  // 获取返回的数据
  HttpEntity entity = httpResponse.getEntity();
  byte[] body = EntityUtils.toByteArray(entity);
  StatusLine sL = httpResponse.getStatusLine();
  int statusCode = sL.getStatusCode();
  if (statusCode == 200) {
   json = new String(body, charset);
   entity.consumeContent();
  } else {
   throw new HttpException("statusCode="+statusCode);
  }
  return json;
} 
    • 通过流的方式

 

/**
  * 发送http get请求
  *
  * @param getUrl
  * @return
  */
  public String sendGetRequest(String getUrl)
  {
   StringBuffer sb = new StringBuffer();
   InputStreamReader isr = null;
   BufferedReader br = null;
   try
   {
     URL url = new URL(getUrl);
     URLConnection urlConnection = url.openConnection();
     urlConnection.setAllowUserInteraction(false);
     isr = new InputStreamReader(url.openStream());
     br = new BufferedReader(isr);
     String line;
     while ((line = br.readLine()) != null)
     {
      sb.append(line);
     }
   }
   catch (IOException e)
   {
     e.printStackTrace();
   }
   finally
   {
     fileOperator.closeResources(isr, br);
   }
   return sb.toString();
  }
}
  • 只发送get请求获取请求结果
  public static String httpGetRequest(String url, String param) {
      StringBuffer result = null;
      BufferedReader in = null;
      try {
        String urlNameString = url + "?" + param;
        System.out.println("请求url:" + urlNameString);
        URL realUrl = new URL(urlNameString);
        // 打开和URL之间的连接 
        URLConnection connection = realUrl.openConnection();
        // 设置通用的请求属性 
        connection.setRequestProperty("accept", "application/json;charset=UTF-8");
        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;
        result = new StringBuffer();
        while ((line = in.readLine()) != null) {
        result.append(line);
        }
      } catch (Exception e) {
      logger.info("发送GET请求出现异常!" + e);
      } finally {
        //释放资源 
        try {
          if (in != null) {
            in.close();
          }
        } catch (Exception e) {
          logger.info("========get请求资源释放失败========");
        }
      }
    return result.toString();
   }
  • 只发送post请求 

 

public static JSONObject post(String url,JSONObject jsonObject){    
         HttpClient client = new DefaultHttpClient();    
         HttpPost post = new HttpPost(url);    
         JSONObject response = null;    
         try {    
             StringEntity s = new StringEntity(jsonObject.toString(),"UTF-8");    
             s.setContentType("application/json");    
             post.setEntity(s);    
                 
             HttpResponse res = client.execute(post);    
             if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){    
                 HttpEntity entity = res.getEntity();    
                 String charset = EntityUtils.getContentCharSet(entity);    
                 response = new JSONObject(new JSONTokener(new InputStreamReader(entity.getContent(),charset)));    
             }    
         } catch (Exception e) {    
             throw new RuntimeException(e);    
         }    
         return response;    
    }

  //main方法测试
  import org.json.JSONObject;
  import org.json.JSONTokener;
  public static void main(String[] rags) throws Exception{
    String url="http://58.132.200.41:8280/teacher/discussion/add.json?token=58e86364c2654798a25038ae22e4e4f3"; 
    String queryString="{\"subjectId\": 1,\"title\": \"测试讨论1\",\"sharedRange\": 1,\"type\": 1,\"same\": false,\"specialId\": 0,\"editPhone\": false,\"contents\": [\"测试讨论内容\"]}";
    //String content=httpPostWithJSON(url, queryString,"utf-8");
    JSONObject json=post(url,new JSONObject(queryString));
    System.out.println(json);
}
  • 发送post请求获取响应结果
/**

* 向指定 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;

  }

}

 

posted @ 2017-11-02 16:12  海棠--依旧  Views(527)  Comments(0Edit  收藏  举报