上面的链接是最新的

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 params) {

try {

InputStream in = httpGet(getParams(urlStr, params));

return in;

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return null;

}

public InputStream reqPost(String urlStr, HashMap params) {

try {

InputStream in = httpPost(urlStr, getParams(params));

return in;

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return null;

}

private String getParams(Map params) throws UnsupportedEncodingException{

int count = params.size();

Iterator 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 params) throws UnsupportedEncodingException {

int count = params.size();

Iterator 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 setParams(Map params) {

Iterator iterator = params.keySet().iterator();

List requestParam = new ArrayList();

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 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 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 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 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上传

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 params){

StringBuilder param = new StringBuilder();

for (Map.Entry 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 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 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 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);

}

}

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐