Http请求

来源:互联网 发布:openstack云计算入门 编辑:程序博客网 时间:2024/06/05 20:35
package ice.utils.v2.http.send;


import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class IceSendUrlBasic {
/**
* Http请求
* @param surl 连接地址
* @param json json数据
* @return 请求结果
*/
protected String sendURL4PostJson(String surl,String json){
return this.sendURL4PostJson(surl, json, null, 0);
}
/**
* Http请求
* @param surl 连接地址
* @param json json数据
* @return 请求结果
*/
protected String sendURL4PostJson(String surl,String json,String encode){
return this.sendURL4PostJson(surl, json,encode,0);
}
/**
* Http请求
* @param surl surl 连接地址
* @param json json json数据
* @param sendnum 失败请求次数
* @return 请求结果
*/
protected String sendURL4PostJson(String surl,String json,String encode,int sendnum){
try {
URL url = new URL(surl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.4) Gecko/20100523 Firefox/3.6.4 QQDownload/1.7");
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
conn.setRequestProperty("Keep-Alive","115");
conn.setRequestProperty("Connection","keep-alive");
conn.setRequestProperty("cache-control","no-cache");
conn.setRequestProperty("Content-Type", "application/requestJson");
if(json != null){
conn.setRequestProperty("Content-Length", json.length()+"");
conn.getOutputStream().write(json.getBytes());
conn.getOutputStream().flush();
conn.getOutputStream().close();
}
int code = conn.getResponseCode(); 
if(code == 200){
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bts = new byte[512];
int len;
while((len = is.read(bts)) > 0){
baos.write(bts,0,len);
}
baos.flush();
baos.close();
if(baos.size() > 0){
String str;
if(encode != null)
str = new String(baos.toByteArray(),encode);
else
str = new String(baos.toByteArray());
return str;
}
}else{
System.out.println(surl+","+code);
}
}catch (Exception e) {
if(e.getLocalizedMessage().equals("Connection timed out") && sendnum < 4){
return this.sendURL4PostJson(surl, json,encode, sendnum++);
}
e.printStackTrace();
}
return null;
}
/**
* 发送Http请求
* @param surl 地址
* @param encode 解析编码格式
* @return 请求页面返回数据
*/
protected String sendurl(String surl,String encode){
try {
URL url = null;
HttpURLConnection hurl = null;
while(true){
url = new URL(surl);
hurl = (HttpURLConnection) url.openConnection();
hurl.setRequestProperty("accept","*/*");
hurl.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.4) Gecko/20100523 Firefox/3.6.4 QQDownload/1.7");
hurl.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
hurl.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
hurl.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
hurl.setRequestProperty("Keep-Alive","115");
hurl.setRequestProperty("Connection","keep-alive");
hurl.setRequestProperty("cache-control","no-cache");
int code = hurl.getResponseCode(); 
if(code == 200){
InputStream is = hurl.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bts = new byte[512];
int len;
while((len = is.read(bts)) > 0){
baos.write(bts,0,len);
}
baos.flush();
baos.close();
if(baos.size() > 0){
String str;
if(encode != null)
str = new String(baos.toByteArray(),encode);
else
str = new String(baos.toByteArray());
return str;
}
}else{
System.out.println(surl+","+code);
}
}
} catch (Exception e) {
return null;
}
}
protected String sendPost(String urlAddress,String params) {
return this.sendPost(urlAddress, params, "utf-8", 0);
}


public String sendPost3(String surl, String xml){
   //从XML文件时取出要请求的数据
      //  InputStream input = MainActivity.class.getResourceAsStream("documentTest4.xml");
        //byte[] data;
        try {
          //  data = new byte[input.available()];
           // input.read(data);
            //把XML的数据转成字符串
            String str=new String(xml);
            System.out.println(str);
            byte[] bb=str.getBytes();
            //请求地址
            URL url = new URL(surl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5 * 1000);//设置超时的时间
            conn.setDoInput(true);
            conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据
            conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
            conn.setRequestProperty("Content-Length", String.valueOf(bb.length));
            conn.connect();
             DataOutputStream out = new DataOutputStream(conn
                        .getOutputStream());
                out.writeBytes(str); //写入请求的字符串
                out.flush();
                out.close();
        //请求返回的状态 
        if(conn.getResponseCode() ==200) {
            System.out.println("yes++");
            //请求返回的数据
            java.io.InputStream in= conn.getInputStream();
                //conn.getInputStream();
            String a=null;
             try {
                byte[] data1 = new byte[in.available()];
                in.read(data1);
                //转成字符串
                a = new String(data1);
             //   System.out.println(a);
                return a;
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } else {
            System.out.println("no++");
        }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
}

protected String sendPost(String urlAddress,String params,String encode,int sendnum){
try {
URL url = new URL(urlAddress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept","*/*");
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
// conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Cache-Control","max-age=0");
conn.setRequestProperty("Connection","keep-alive");
conn.setRequestProperty("X-Requested-With","XMLHttpRequest");
conn.setRequestProperty("Host","mp.weixin.qq.com");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
HttpURLConnection.setFollowRedirects(true);
if(params != null){
//conn.setRequestProperty("Content-Length", params.length()+"");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(params);
out.flush();
out.close();
}
conn.connect();
int code = conn.getResponseCode(); 
if(code == 200){
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bts = new byte[512];
int len;
while((len = is.read(bts)) > 0){
baos.write(bts,0,len);
}
baos.flush();
baos.close();
if(baos.size() > 0){
String str;
if(encode != null)
str = new String(baos.toByteArray(),encode);
else
str = new String(baos.toByteArray());
return str;
}
}else{
System.out.println(url+","+code);
}
}catch (Exception e) {
if(e.getLocalizedMessage().equals("Connection timed out") && sendnum < 4){
return this.sendURL4PostJson(urlAddress, params,encode, sendnum++);
}
e.printStackTrace();
}
return null; 
}
public static void main(String[] args) {
try {
StringBuffer url = new StringBuffer("http://127.0.0.1/PServ/blogin");
url.append("?cname=").append(URLEncoder.encode("开发人员","UTF-8"));
url.append("&uname=").append(URLEncoder.encode("icesongs", "UTF-8"));
url.append("&upwd=").append(URLEncoder.encode("ice2jing", "UTF-8"));
String res = new IceSendUrlBasic().sendurl(url.toString(), "UTF-8");
System.out.println(res);
System.out.println(url.toString());
} catch (Exception e) {
e.printStackTrace();
}

}
}
0 0
原创粉丝点击