http请求

来源:互联网 发布:350淘宝模板破解 编辑:程序博客网 时间:2024/06/08 18:53
packagecom.hes.tools.net.httpnet;
 
importjava.io.ByteArrayOutputStream;
importjava.io.DataOutputStream;
importjava.io.InputStream;
importjava.io.UnsupportedEncodingException;
importjava.net.HttpURLConnection;
importjava.net.URL;
importjava.net.URLEncoder;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importorg.apache.http.HttpEntity;
importorg.apache.http.HttpResponse;
importorg.apache.http.HttpStatus;
importorg.apache.http.HttpVersion;
importorg.apache.http.client.HttpClient;
importorg.apache.http.client.entity.UrlEncodedFormEntity;
importorg.apache.http.client.methods.HttpGet;
importorg.apache.http.client.methods.HttpPost;
importorg.apache.http.client.utils.URLEncodedUtils;
importorg.apache.http.conn.ClientConnectionManager;
importorg.apache.http.conn.params.ConnManagerParams;
importorg.apache.http.conn.scheme.PlainSocketFactory;
importorg.apache.http.conn.scheme.Scheme;
importorg.apache.http.conn.scheme.SchemeRegistry;
importorg.apache.http.conn.ssl.SSLSocketFactory;
importorg.apache.http.impl.client.DefaultHttpClient;
importorg.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
importorg.apache.http.message.BasicNameValuePair;
importorg.apache.http.params.BasicHttpParams;
importorg.apache.http.params.HttpConnectionParams;
importorg.apache.http.params.HttpParams;
importorg.apache.http.params.HttpProtocolParams;
importorg.apache.http.protocol.HTTP;
importorg.apache.http.util.EntityUtils;
 
importandroid.util.Log;
 
publicclass HttpRequest {
 
    privatestatic HttpRequest httpRequest;
    privateHttpClient httpClient;
 
    privateHttpRequest() {
        httpClient = getHttpClient();
    }
 
    publicstatic HttpRequest getHttRequest() {
        if(httpRequest == null) {
            httpRequest = newHttpRequest();
        }
        returnhttpRequest;
    }
 
    privateInputStream httpGet(String urlStr) {
        try{
            URL url = newURL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("connection","Keep-Alive");
            connection.setRequestProperty("Charsert","UTF-8");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.setRequestMethod("GET");
            if(connection.getResponseCode() != HttpStatus.SC_OK) {
                returnnull;
            }
            InputStream inStream = connection.getInputStream();
            if(inStream != null) {
                ByteArrayOutputStream outStream = newByteArrayOutputStream();
                byte[] buffer = newbyte[1024];
                intlen = 0;
                while((len = inStream.read(buffer)) != -1) {
                    outStream.write(buffer,0, len);
                }
                inStream.close();
                Log.d("DATA",newString(outStream.toByteArray()));
                returninStream;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnnull;
    }
 
    privateInputStream httpPost(String urlStr, String content) {
        try{
            URL url = newURL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            connection.setDoInput(true);
            // Post 请求不能使用缓存
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
            // 意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
            // 进行编码
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("connection","Keep-Alive");
            connection.setRequestProperty("Charsert","UTF-8");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);
            connection.setRequestMethod("POST");
            DataOutputStream out = newDataOutputStream(connection.getOutputStream());
            out.writeBytes(content);
            out.flush();
            out.close();
            if(connection.getResponseCode() != HttpStatus.SC_OK) {
                returnnull;
            }
            InputStream inStream = connection.getInputStream();
            if(inStream != null) {
                ByteArrayOutputStream outStream = newByteArrayOutputStream();
                byte[] buffer = newbyte[1024];
                intlen = 0;
                while((len = inStream.read(buffer)) != -1) {
                    outStream.write(buffer,0, len);
                }
                inStream.close();
                Log.d("DATA",newString(outStream.toByteArray()));
                returninStream;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnnull;
    }
 
    publicInputStream reqGet(String urlStr, HashMap<String, String> params) {
        try{
            InputStream in = httpGet(getParams(urlStr, params));
            returnin;
        }catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        returnnull;
    }
     
    publicInputStream reqPost(String urlStr, HashMap<String, String> params) {
        try{
            InputStream in = httpPost(urlStr, getParams(params));
            returnin;
        }catch(UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        returnnull;
    }
     
    privateString getParams(Map<String, String> params) throwsUnsupportedEncodingException{
        intcount = params.size();
        Iterator<String> iterator = params.keySet().iterator();
        StringBuffer sb = newStringBuffer();
        String param = "";
        String value = "";
        intc = 0;
        while(iterator.hasNext()) {
            param = iterator.next();
            sb.append(param);
            sb.append("=");
            value = params.get(param);
            sb.append(URLEncoder.encode(value,"UTF-8"));
            c++;
            if(c != count) {
                sb.append("&");
            }
        }
        count = c = 0;
        String reqUrl = sb.toString();
        returnreqUrl;
    }
 
    privateString getParams(String urlStr, Map<String, String> params) throwsUnsupportedEncodingException {
        intcount = params.size();
        Iterator<String> iterator = params.keySet().iterator();
        StringBuffer sb = newStringBuffer();
        String param = "";
        String value = "";
        sb.append(urlStr);
        sb.append("?");
        intc = 0;
        while(iterator.hasNext()) {
            param = iterator.next();
            sb.append(param);
            sb.append("=");
            value = params.get(param);
            sb.append(URLEncoder.encode(value,"UTF-8"));
            c++;
            if(c != count) {
                sb.append("&");
            }
        }
        count = c = 0;
        String reqUrl = sb.toString();
        returnreqUrl;
    }
 
    privateList<BasicNameValuePair> setParams(Map<String, String> params) {
        Iterator<String> iterator = params.keySet().iterator();
        List<BasicNameValuePair> requestParam = newArrayList<BasicNameValuePair>();
        String param = "";
        String value = "";
        while(iterator.hasNext()) {
            param = iterator.next();
            value = params.get(param);
            requestParam.add(newBasicNameValuePair(param, value));
        }
        returnrequestParam;
    }
 
    publicHttpEntity httpPost(String url, Map<String, String> params) {
        try{
            HttpPost post = newHttpPost(url);
            post.setEntity(newUrlEncodedFormEntity(setParams(params), "UTF-8"));
            HttpResponse response = httpClient.execute(post);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                thrownew Exception("response code not 200");
            }
            HttpEntity entity = response.getEntity();
            if(entity != null) {
                returnentity;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnnull;
    }
 
    publicHttpEntity httpGet(String url, Map<String, String> params) {
        try{
            String param = URLEncodedUtils.format(setParams(params), "UTF-8");
            HttpGet get = newHttpGet(url + "?"+ param);
            HttpResponse response = httpClient.execute(get);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                thrownew Exception("response code not 200");
            }
            HttpEntity entity = response.getEntity();
            if(entity != null) {
                returnentity;
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnnull;
    }
 
    publicString getString(String url, Map<String, String> params, String method) {
        HttpEntity entity = null;
        if(method.toUpperCase().equals("GET")) {
            entity = httpGet(url, params);
        }else{
            entity = httpPost(url, params);
        }
        String str = null;
        try{
            if(entity != null) {
                str = EntityUtils.toString(entity, "UTF-8");
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnstr;
    }
 
    publicbyte[] getArray(String url, Map<String, String> params, String method) {
        HttpEntity entity = null;
        if(method.toUpperCase().equals("GET")) {
            entity = httpGet(url, params);
        }else{
            entity = httpPost(url, params);
        }
        byte[] bytes = null;
        try{
            if(entity != null) {
                bytes = EntityUtils.toByteArray(entity);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        returnbytes;
    }
 
    publicHttpClient getHttpClient() {
        HttpParams params = newBasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpProtocolParams.setUseExpectContinue(params,true);
        HttpProtocolParams.setUserAgent(params,"Mozilla/5.0(Linux;U;Android 2.3.3;en-us;Nexus One Build.FRG83) AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
        // 超时设置
        /* 从连接池中取连接的超时时间 */
        ConnManagerParams.setTimeout(params,5000);
        /* 连接超时 */
        HttpConnectionParams.setConnectionTimeout(params,5000);
        /* 请求超时 */
        HttpConnectionParams.setSoTimeout(params,5000);
        // 设置HttpClient支持HTTP和HTTPS两种模式
        SchemeRegistry schReg = newSchemeRegistry();
        schReg.register(newScheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(newScheme("https", SSLSocketFactory.getSocketFactory(), 443));
        // 使用线程安全的连接管理来创建HttpClient
        ClientConnectionManager conMgr = newThreadSafeClientConnManager(params, schReg);
        HttpClient httpClient = newDefaultHttpClient(conMgr, params);
        returnhttpClient;
    }
}

socket上传


?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
packagecom.hes.tools.net.upload;
 
importjava.io.File;
importjava.util.Map;
 
publicclass HttpHoder {
     
    protectedbyte[] createHeaders(longlenth){
        String header = String.format(
        "POST /Manager/WebService/UploadmediaService.aspx HTTP/1.1\r\n" +
        "keep-alive: true\r\n" +
        "connection: keep-alive\r\n" +
        "charset: UTF-8\r\n" +
        "content-type: multipart/form-data; boundary=---------7d4a6d158c9\r\n" +
        "User-Agent: Dalvik/1.2.0 (Linux; U; Android 2.2; sdk Build/FRF91)\r\n" +
        "Host: 192.168.1.103\r\n" +
        "Content-Length: %d" +
        "\r\n\r\n", lenth);
        returnheader.getBytes();
    }
     
    protectedbyte[] createHeaders(String content_lenth, String host){
        StringBuilder header = newStringBuilder();
        header.append("POST /Manager/WebService/UploadmediaService.aspx HTTP/1.1\r\n");
        header.append("HOST: "+host+"\r\n");
        header.append("Connection: keep-alive\r\n");
        header.append("Keep-Alive: true\r\n");
        header.append("Accept: */*\r\n");
        header.append("Accept-Language: zh-cn\r\n");
        header.append("Accept-Charset: utf-8\r\n");
        header.append("User-Agent: Dalvik/1.2.0 (Linux; U; Android 2.2; sdk Build/FRF91)\r\n");
        header.append("Content-Type: multipart/form-data; boundary=---------7d4a6d158c9\r\n");
        header.append("Content-Length: " + content_lenth);
        header.append("\r\n\r\n");
        byte[] byte_header = header.toString().getBytes();
        returnbyte_header;
    }
     
    protectedbyte[] createParamsContent(Map<String, String> params){
        StringBuilder param = newStringBuilder();
        for(Map.Entry<String, String> entry : params.entrySet()) {
            param.append("-----------7d4a6d158c9\r\n");
            param.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
            param.append(entry.getValue());
            param.append("\r\n");
        }
        byte[] bytes = param.toString().getBytes();
        returnbytes;
    }
     
    protectedbyte[] createFileHeaderBoundary(String fileName) {
        StringBuilder builder = newStringBuilder();
        builder.append("-----------7d4a6d158c9\r\n");
        builder.append("Content-Disposition: form-data;name=\"" + fileName + "\";filename=\""+ fileName + "\"\r\n");
        builder.append("Content-Type: application/octet-stream");
        builder.append("\r\n\r\n");
        byte[] bytes = builder.toString().getBytes();
        returnbytes;
    }
     
    protectedbyte[] getFileHeaderBoundary(String fileName) {
        StringBuilder builder = newStringBuilder();
        builder.append("-----------7d4a6d158c9\r\n");
        builder.append("Content-Disposition: form-data;name=\"" + fileName + "\";filename=\""+ fileName + "\"\r\n");
        builder.append("Content-Type: application/octet-stream");
        builder.append("\r\n\r\n");
        byte[] bytes = builder.toString().getBytes();
        returnbytes;
    }
     
    protectedbyte[] createContentEnd(){
        byte[] after = ("\r\n-----------7d4a6d158c9--\r\n").getBytes();
        returnafter;
    }
     
    protectedlong getFileLengths(File file){
        returnfile.length();
    }
 
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
packagecom.hes.tools.net.upload;
 
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.net.Socket;
importjava.net.UnknownHostException;
importjava.util.Map;
importandroid.util.Log;
 
publicclass HttpUploadSocket extendsHttpHoder {
 
    privateSocket mSocket;
    privateMap<String, String> params;
    privateFile file;
    privateString host;
    privateint port;
    privateint bytesize = 1024* 1024;
    privateFileInputStream fis;
    privateOutputStream out;
    privateInputStream is;
 
    publicHttpUploadSocket(Map<String, String> params, File file, String host, intport) {
        this.params = params;
        this.file = file;
        this.host = host;
        this.port = port;
    }
 
    publicvoid run() {
        try{
            String fileName = file.getName();
            fis = newFileInputStream(file);
            longlength = file.length();
            intsize = (int) (length / bytesize) + 1;
            byte[] in = newbyte[bytesize];
            for(inti = 0; i < size; i++) {
                intlen = 0;
                while((len = fis.read(in)) != -1) {
                    socketUpload(params, in, fileName, host, port, len);
                }
            }
            Log.d("SOCKET","获得InputStream");
            is = mSocket.getInputStream();
            byte[] b = newbyte[1024* 10];
            intlen = 0;
            while((len = is.read(b)) != -1) {
                Log.d("SOCKET","InputStream return " + newString(b, 0, len));
                break;
            }
            Log.d("SOCKET","close socket");
        }catch(Exception e) {
            // TODO: handle exception
        }finally{
            try{
                out.close();
                is.close();
                mSocket.close();
            }catch(Exception e2) {
            }
        }
    }
 
    privatevoid socketUpload(Map<String, String> params, byte[] filebyte, String fileName, String host, intport, intlen) throwsUnknownHostException, IOException {
        byte[] param = this.createParamsContent(params);// 参数byte数组
        byte[] fileBoundary = this.createFileHeaderBoundary(fileName);// 文件头byte数组
        byte[] endBoundary = this.createContentEnd();// 结束byte[]数组
        longfileLenths = len;// 文件Byte数组长度
        String countLengths = String.valueOf(param.length + fileBoundary.length + fileLenths + endBoundary.length);
        byte[] heand = this.createHeaders(countLengths, host);// 头byte数组
        Log.d("SOCKET","param="+ param.length + " fileBoundary "
                + fileBoundary.length + " endBoundary " + endBoundary.length
                +" fileLenths" + fileLenths);
        connect(host, port);// 连接
        Log.d("SOCKET","获得OutputStream");
        out = mSocket.getOutputStream();
        Log.d("SOCKET","写头文件");
        out.write(heand,0, heand.length);
        Log.d("SOCKET","头文件写入完成!");
        Log.d("SOCKET","写参数");
        out.write(param,0, param.length);
        Log.d("SOCKET","参数写入完成!");
        Log.d("SOCKET","写开始文件分割线");
        out.write(fileBoundary,0, fileBoundary.length);
        Log.d("SOCKET","文件分割线写入完成!");
        Log.d("SOCKET","写文件");
        out.write(filebyte,0, len);
        Log.d("SOCKET","文件写入完成!");
        Log.d("SOCKET","写结尾文件分割线");
        out.write(endBoundary,0, endBoundary.length);
        Log.d("SOCKET","结尾文件分割线写入完成!");
        Log.d("SOCKET","上传完毕!");
    }
 
    privatevoid connect(String host, intport) throwsUnknownHostException, IOException {
        if(mSocket == null) {
            Log.d("SOCKET","建立 socket 连接");
            mSocket = newSocket(host, port);
            mSocket.setSoTimeout(10000);
            mSocket.setKeepAlive(true);
            mSocket.setReuseAddress(true);
        }else{
            Log.d("SOCKET","socket 已连接");
        }
    }
 
    publicvoid removeFile(String path) {
        File file = newFile(path);
        if(file.exists() && file.isFile()) {
            if(file.delete()) {
                Log.i("SOCKET","删除文件"+ path);
            }
        }
    }
}
0 0
原创粉丝点击