android的Http請求組件

https://github.com/spacetimeme/android-network/blob/develop/library/src/main/java/android/network/http/Http.javajava

上面的連接是最新的android

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上傳c++

 

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();
	}

}
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);
			}
		}
	}
}
相關文章
相關標籤/搜索