发起post、get请求

 HttpURLConnection对象

/*** 
* 发起post请求,传输xml数据
* @param strUrl 请求地址
* @param xml 发送数据
* @return string 对方服务器返回数据
*/ 
public static String PostByHttpURLConnection(String strUrl, String xml) {
  HttpURLConnection conn;
  try {
    URL url = new URL(strUrl);
    conn = (HttpURLConnection) url.openConnection();
    // 设置是否从httpUrlConnection读入,默认情况下是true; 
    conn.setDoInput(true);
    // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false; 
    conn.setDoOutput(true);
    // 设定请求的方法为"POST",默认是GET 
    conn.setRequestMethod("POST");
    //设置超时
    conn.setConnectTimeout(3000);
    conn.setReadTimeout(4000);
    // Post 请求不能使用缓存 
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    // 设定传送的内容类型是可序列化的java对象 
    conn.setRequestProperty("Content-Type","text/xml");
    conn.setRequestProperty("Pragma:", "no-cache"); 
    conn.setRequestProperty("Cache-Control", "no-cache");
    conn.setRequestProperty("charset", "utf-8");

    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(new String(xml.getBytes("utf-8")));
    out.flush();
    out.close();

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String line = ""; 
    StringBuilder sb = new StringBuilder();
    for (line = br.readLine(); line != null; line = br.readLine()) { 
      //System.out.println(line); 
      sb.append(line);
    } 
    return sb.toString();
  } catch (IOException ex) { 
    ex.printStackTrace();
    return "error";
  }
}
 
原文地址:https://www.cnblogs.com/sweetyu/p/5408002.html