HTTP - post & get 第二篇

package cn.itcast.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class SocketHttpRequester {
    /**
     * 发送xml数据
     * @param actionUrl 请求地址
     * @param xml xml数据
     * @param encoding 编码
     * @return
     * @throws Exception
     */
    public static byte[] postXml(String actionUrl, String xml, String encoding) throws Exception{
        byte[] data = xml.getBytes(encoding);
        URL url = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setConnectTimeout(5 * 1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        if(conn.getResponseCode()==200){
            return NetTool.readStream(conn.getInputStream());
        }
        return null;
    }
   
    /**
     * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
     *   <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data">
            <INPUT TYPE="text" NAME="name">
            <INPUT TYPE="text" NAME="id">
            <input type="file" name="imagefile"/>
            <input type="file" name="zip"/>
         </FORM>
     * @param actionUrl 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
     * @param params 请求参数 key为参数名,value为参数值
     * @param file 上传文件
     */
    public static boolean post(String actionUrl, Map<String, String> params, FormFile[] files) {
        try {           
            final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
            final String endline = "--" + BOUNDARY + "--/r/n";//数据结束标志
            URL url = new URL(actionUrl);
            Socket socket = new Socket(InetAddress.getByName(url.getHost()), url.getPort());          
            OutputStream outStream = socket.getOutputStream();
            String posthead = "POST "+ url.getPath()+" HTTP/1.1/r/n";
            outStream.write(posthead.getBytes());
            String language = "Accept-Language: zh-CN/r/n";
            outStream.write(language.getBytes());
            String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "/r/n";
            outStream.write(contenttype.getBytes());
            String alive = "Connection: Keep-Alive/r/n";
            outStream.write(alive.getBytes());
            String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*/r/n";
            outStream.write(accept.getBytes());
            String host = "Host: "+ url.getHost() +":"+ url.getPort() +"/r/n";
            outStream.write(host.getBytes());
            int filetotallength = 0;//得到所有文件的总大小
            for(FormFile file : files){
                StringBuilder split = new StringBuilder();
                 split.append("--");
                 split.append(BOUNDARY);
                 split.append("/r/n");
                 split.append("Content-Disposition: form-data;name=/""+ file.getFormname()+"/";filename=/""+ file.getFilname() + "/"/r/n");
                 split.append("Content-Type: "+ file.getContentType()+"/r/n/r/n");
                 split.append("/r/n");
                 filetotallength += split.length();
                if(file.getInStream()!=null){
                     filetotallength += file.getFile().length();
                 }else{
                     filetotallength += file.getData().length;
                 }
            }
            / 写文本类型请求参数/
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("/r/n");
                sb.append("Content-Disposition: form-data; name=/""+ entry.getKey() + "/"/r/n/r/n");
                sb.append(entry.getValue());
                sb.append("/r/n");
            }
            int length = sb.toString().getBytes().length + filetotallength +  endline.getBytes().length;
            String contentlength = "Content-Length: "+ length + "/r/n";
            outStream.write(contentlength.getBytes());
            outStream.write("/r/n".getBytes());
            outStream.write(sb.toString().getBytes());
          
            // 写文件类型请求参数/
            for(FormFile file : files){//发送文件数据
                StringBuilder split = new StringBuilder();
                 split.append("--");
                 split.append(BOUNDARY);
                 split.append("/r/n");
                 split.append("Content-Disposition: form-data;name=/""+ file.getFormname()+"/";filename=/""+ file.getFilname() + "/"/r/n");
                 split.append("Content-Type: "+ file.getContentType()+"/r/n/r/n");
                 outStream.write(split.toString().getBytes());
                 if(file.getInStream()!=null){
                     byte[] buffer = new byte[1024];
                     int len = 0;
                     while((len = file.getInStream().read(buffer, 0, 1024))!=-1){
                         outStream.write(buffer, 0, len);
                     }
                     file.getInStream().close();
                 }else{
                     outStream.write(file.getData(), 0, file.getData().length);
                 }
                 outStream.write("/r/n".getBytes());
            }    
            outStream.write(endline.getBytes());
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            if(in.readLine().indexOf("200")==-1){
                return false;
            }
            outStream.flush();
            outStream.close();
            in.close();
            socket.close();
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
   
    /**
     * 提交数据到服务器
     * @param actionUrl 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
     * @param params 请求参数 key为参数名,value为参数值
     * @param file 上传文件
     */
    public static boolean post(String actionUrl, Map<String, String> params, FormFile file) {
       return post(actionUrl, params, new FormFile[]{file});
    }
   
    public static byte[] postFromHttpClient(String path, Map<String, String> params, String encode) throws Exception{
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();//用于存放请求参数
        for(Map.Entry<String, String> entry : params.entrySet()){
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, encode);
        HttpPost httppost = new HttpPost(path);
        httppost.setEntity(entity);
        HttpClient httpclient = new DefaultHttpClient();//看作是浏览器
        HttpResponse response = httpclient.execute(httppost);//发送post请求       
        return NetTool.readStream(response.getEntity().getContent());
    }

    /**
     * 发送请求
     * @param path 请求路径
     * @param params 请求参数 key为参数名称 value为参数值
     * @param encode 请求参数的编码
     */
    public static byte[] post(String path, Map<String, String> params, String encode) throws Exception{
        //String params = "method=save&name="+ URLEncoder.encode("老毕", "UTF-8")+ "&age=28&";//需要发送的参数
        StringBuilder parambuilder = new StringBuilder("");
        if(params!=null && !params.isEmpty()){
            for(Map.Entry<String, String> entry : params.entrySet()){
                parambuilder.append(entry.getKey()).append("=")
                    .append(URLEncoder.encode(entry.getValue(), encode)).append("&");
            }
            parambuilder.deleteCharAt(parambuilder.length()-1);
        }
        byte[] data = parambuilder.toString().getBytes();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);//允许对外发送请求参数
        conn.setUseCaches(false);//不进行缓存
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("POST");
        //下面设置http请求头
        conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setRequestProperty("Connection", "Keep-Alive");
       
        //发送参数
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(data);//把参数发送出去
        outStream.flush();
        outStream.close();
        if(conn.getResponseCode()==200){
            return NetTool.readStream(conn.getInputStream());
        }
        return null;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值