http请求

package com.hes.tools.net.httpnet;
 
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
 
import android.util.Log;
 
public class HttpRequest {
 
     private static HttpRequest httpRequest;
     private HttpClient httpClient;
 
     private HttpRequest() {
         httpClient = getHttpClient();
     }
 
     public static HttpRequest getHttRequest() {
         if (httpRequest == null ) {
             httpRequest = new HttpRequest();
         }
         return httpRequest;
     }
 
     private InputStream httpGet(String urlStr) {
         try {
             URL url = new URL(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) {
                 return null ;
             }
             InputStream inStream = connection.getInputStream();
             if (inStream != null ) {
                 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                 byte [] buffer = new byte [ 1024 ];
                 int len = 0 ;
                 while ((len = inStream.read(buffer)) != - 1 ) {
                     outStream.write(buffer, 0 , len);
                 }
                 inStream.close();
                 Log.d( "DATA" , new String(outStream.toByteArray()));
                 return inStream;
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return null ;
     }
 
     private InputStream httpPost(String urlStr, String content) {
         try {
             URL url = new URL(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 = new DataOutputStream(connection.getOutputStream());
             out.writeBytes(content);
             out.flush();
             out.close();
             if (connection.getResponseCode() != HttpStatus.SC_OK) {
                 return null ;
             }
             InputStream inStream = connection.getInputStream();
             if (inStream != null ) {
                 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                 byte [] buffer = new byte [ 1024 ];
                 int len = 0 ;
                 while ((len = inStream.read(buffer)) != - 1 ) {
                     outStream.write(buffer, 0 , len);
                 }
                 inStream.close();
                 Log.d( "DATA" , new String(outStream.toByteArray()));
                 return inStream;
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return null ;
     }
 
     public InputStream reqGet(String urlStr, HashMap<String, String> params) {
         try {
             InputStream in = httpGet(getParams(urlStr, params));
             return in;
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         }
         return null ;
     }
     
     public InputStream reqPost(String urlStr, HashMap<String, String> params) {
         try {
             InputStream in = httpPost(urlStr, getParams(params));
             return in;
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         }
         return null ;
     }
     
     private String getParams(Map<String, String> params) throws UnsupportedEncodingException{
         int count = params.size();
         Iterator<String> iterator = params.keySet().iterator();
         StringBuffer sb = new StringBuffer();
         String param = "" ;
         String value = "" ;
         int c = 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();
         return reqUrl;
     }
 
     private String getParams(String urlStr, Map<String, String> params) throws UnsupportedEncodingException {
         int count = params.size();
         Iterator<String> iterator = params.keySet().iterator();
         StringBuffer sb = new StringBuffer();
         String param = "" ;
         String value = "" ;
         sb.append(urlStr);
         sb.append( "?" );
         int c = 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();
         return reqUrl;
     }
 
     private List<BasicNameValuePair> setParams(Map<String, String> params) {
         Iterator<String> iterator = params.keySet().iterator();
         List<BasicNameValuePair> requestParam = new ArrayList<BasicNameValuePair>();
         String param = "" ;
         String value = "" ;
         while (iterator.hasNext()) {
             param = iterator.next();
             value = params.get(param);
             requestParam.add( new BasicNameValuePair(param, value));
         }
         return requestParam;
     }
 
     public HttpEntity httpPost(String url, Map<String, String> params) {
         try {
             HttpPost post = new HttpPost(url);
             post.setEntity( new UrlEncodedFormEntity(setParams(params), "UTF-8" ));
             HttpResponse response = httpClient.execute(post);
             if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                 throw new Exception( "response code not 200" );
             }
             HttpEntity entity = response.getEntity();
             if (entity != null ) {
                 return entity;
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return null ;
     }
 
     public HttpEntity httpGet(String url, Map<String, String> params) {
         try {
             String param = URLEncodedUtils.format(setParams(params), "UTF-8" );
             HttpGet get = new HttpGet(url + "?" + param);
             HttpResponse response = httpClient.execute(get);
             if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                 throw new Exception( "response code not 200" );
             }
             HttpEntity entity = response.getEntity();
             if (entity != null ) {
                 return entity;
             }
         } catch (Exception e) {
             e.printStackTrace();
         }
         return null ;
     }
 
     public String 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();
         }
         return str;
     }
 
     public byte [] 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();
         }
         return bytes;
     }
 
     public HttpClient getHttpClient() {
         HttpParams params = new BasicHttpParams();
         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 = new SchemeRegistry();
         schReg.register( new Scheme( "http" , PlainSocketFactory.getSocketFactory(), 80 ));
         schReg.register( new Scheme( "https" , SSLSocketFactory.getSocketFactory(), 443 ));
         // 使用线程安全的连接管理来创建HttpClient
         ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
         HttpClient httpClient = new DefaultHttpClient(conMgr, params);
         return httpClient;
     }
}

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
package com.hes.tools.net.upload;
 
import java.io.File;
import java.util.Map;
 
public class HttpHoder {
     
     protected byte [] createHeaders( long lenth){
         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);
         return header.getBytes();
     }
     
     protected byte [] createHeaders(String content_lenth, String host){
         StringBuilder header = new StringBuilder();
         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();
         return byte_header;
     }
     
     protected byte [] createParamsContent(Map<String, String> params){
         StringBuilder param = new StringBuilder();
         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();
         return bytes;
     }
     
     protected byte [] createFileHeaderBoundary(String fileName) {
         StringBuilder builder = new StringBuilder();
         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();
         return bytes;
     }
     
     protected byte [] getFileHeaderBoundary(String fileName) {
         StringBuilder builder = new StringBuilder();
         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();
         return bytes;
     }
     
     protected byte [] createContentEnd(){
         byte [] after = ( "\r\n-----------7d4a6d158c9--\r\n" ).getBytes();
         return after;
     }
     
     protected long getFileLengths(File file){
         return file.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
package com.hes.tools.net.upload;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Map;
import android.util.Log;
 
public class HttpUploadSocket extends HttpHoder {
 
     private Socket mSocket;
     private Map<String, String> params;
     private File file;
     private String host;
     private int port;
     private int bytesize = 1024 * 1024 ;
     private FileInputStream fis;
     private OutputStream out;
     private InputStream is;
 
     public HttpUploadSocket(Map<String, String> params, File file, String host, int port) {
         this .params = params;
         this .file = file;
         this .host = host;
         this .port = port;
     }
 
     public void run() {
         try {
             String fileName = file.getName();
             fis = new FileInputStream(file);
             long length = file.length();
             int size = ( int ) (length / bytesize) + 1 ;
             byte [] in = new byte [bytesize];
             for ( int i = 0 ; i < size; i++) {
                 int len = 0 ;
                 while ((len = fis.read(in)) != - 1 ) {
                     socketUpload(params, in, fileName, host, port, len);
                 }
             }
             Log.d( "SOCKET" , "获得InputStream" );
             is = mSocket.getInputStream();
             byte [] b = new byte [ 1024 * 10 ];
             int len = 0 ;
             while ((len = is.read(b)) != - 1 ) {
                 Log.d( "SOCKET" , "InputStream return " + new String(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) {
             }
         }
     }
 
     private void socketUpload(Map<String, String> params, byte [] filebyte, String fileName, String host, int port, int len) throws UnknownHostException, IOException {
         byte [] param = this .createParamsContent(params); // 参数byte数组
         byte [] fileBoundary = this .createFileHeaderBoundary(fileName); // 文件头byte数组
         byte [] endBoundary = this .createContentEnd(); // 结束byte[]数组
         long fileLenths = 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" , "上传完毕!" );
     }
 
     private void connect(String host, int port) throws UnknownHostException, IOException {
         if (mSocket == null ) {
             Log.d( "SOCKET" , "建立 socket 连接" );
             mSocket = new Socket(host, port);
             mSocket.setSoTimeout( 10000 );
             mSocket.setKeepAlive( true );
             mSocket.setReuseAddress( true );
         } else {
             Log.d( "SOCKET" , "socket 已连接" );
         }
     }
 
     public void removeFile(String path) {
         File file = new File(path);
         if (file.exists() && file.isFile()) {
             if (file.delete()) {
                 Log.i( "SOCKET" , "删除文件" + path);
             }
         }
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值