http协议上传数据的 优化 方法

package com.example.http.all;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.net.ssl.SSLHandshakeException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.example.progress.R;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

public class MyHttp extends Activity{


private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount,HttpContext context) {
if (executionCount >= 3) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};


private static ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
String charset = EntityUtils.getContentCharSet(entity) == null ? "UTU-8" : EntityUtils.getContentCharSet(entity);
return new String(EntityUtils.toByteArray(entity), charset);
} else {
return null;
}
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);



try {
String url = "http://192.168.1.104:8888/mytestweb_json/getJson.do?flag=getjson";



OutputStream out = this.openFileOutput("zgt.xml", Context.MODE_WORLD_READABLE);

byte[] buffer =url.getBytes();


out.write(buffer);

//File file = new File("com.example.progress/files/zgt.xml");

// InputStream input =this.openFileInput("zgt.xml");
//
// String string2 = "";
//
// byte [] bytes = new byte[1024];
// int len=0;
// while((len = input.read(bytes))!=-1){
// String string = new String(bytes, 0, len);
// string2+=string;
//
// }
// String string = postSendInput(url, input, string2.length(), "UTF-8");

// String string = postSend(url, "dddddddddddddddddddddddddddddddddddddddddd", "UTF-8");

File file = new File("/sdcard/2623176_081339027_2.gif");

InputStream input = new FileInputStream(file);

String string = postSendInput(url, input, file.length(), "UTF-8");

//String string = postSendFile(url, file, "UTF-8");

System.out.println(string);
} catch (Exception e) {
e.printStackTrace();
}

}



//创建 DefaultHttpClient 对象
private static DefaultHttpClient getDefaultHttpClient(final String charset) {

DefaultHttpClient httpclient = new DefaultHttpClient();

httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET,charset == null ? "UTF-8" : charset);
httpclient.setHttpRequestRetryHandler(requestRetryHandler);

return httpclient;
}


/**
*@title 向服务器发送数据
* @param url
* @param data 要发送的数据
* @param charset 编码方式
* @return 服务器返回的数据
*/
public static String postSend(String url,String data,String charset) {
if (url == null || url.trim().length()==0) {
return null;
}
DefaultHttpClient httpclient = getDefaultHttpClient(charset);
StringEntity formEntity = null;
try {
if (charset == null || charset.trim().length()==0) {
formEntity = new StringEntity(data);
} else {
formEntity = new StringEntity(data,charset);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpPost hp = new HttpPost(url);
hp.setEntity(formEntity);
try {
return httpclient.execute(hp, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
abortConnection(hp, httpclient);
}
return null;
}












/***
* 向服务器传递数据流
* @param url
* @param input
* @param length
* @param charset
* @return
*/
public static String postSendInput(String url,InputStream input,long length,String charset) {
if (url == null || url.trim().length()==0) {
return null;
}
DefaultHttpClient httpclient = getDefaultHttpClient(charset);
HttpEntity formEntity = null;
try {
formEntity =new InputStreamEntity(input, length);
} catch (Exception e) {
e.printStackTrace();
}

HttpPost hp = new HttpPost(url);
hp.setEntity(formEntity);
try {
return httpclient.execute(hp, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
abortConnection(hp, httpclient);
}
return null;
}


/***
* 向服务器传递数据流
* @param url
* @param input
* @param length
* @param charset
* @return
*/
public static String postSendFile(String url,File file,String charset) {
if (url == null || url.trim().length()==0) {
return null;
}
DefaultHttpClient httpclient = getDefaultHttpClient(charset);
HttpEntity formEntity = null;
try {
formEntity =new FileEntity(file, "binary/octet-stream");
} catch (Exception e) {
e.printStackTrace();
}

HttpPost hp = new HttpPost(url);
hp.setEntity(formEntity);
try {
return httpclient.execute(hp, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
abortConnection(hp, httpclient);
}
return null;
}





private static void abortConnection(final HttpRequestBase hrb,final HttpClient httpclient) {
if (hrb != null) {
hrb.abort();
}
if (httpclient != null) {
httpclient.getConnectionManager().shutdown();
}
}


}

原文地址:https://www.cnblogs.com/zhangguangtao/p/3010338.html