1. 程式人生 > >HTTP傳輸byte[ ] 兩種方式

HTTP傳輸byte[ ] 兩種方式

//========第一種========
public class HttpUtil {
    public static InputStream http(String url, byte[] PostData) {
        URL u = null;
        HttpURLConnection con = null;
        InputStream inputStream = null;
        //嘗試傳送請求
        try {
            u = new URL(url);
            con = (HttpURLConnection) u.openConnection();
            con.setRequestMethod(“POST”);
            con.setDoOutput(true
); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty(“Content-Type”, “binary/octet-stream”); OutputStream outStream = con.getOutputStream(); outStream.write(PostData); outStream.flush(); outStream.close(); //讀取返回內容
inputStream = con.getInputStream(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { con.disconnect(); } return inputStream; } } //==========第二種============ public String postUrlByByteArray(Context context, byte
[] paramArrayOfByte, String url, String httpPostId) { String result = ""; HttpPost httpPost = new HttpPost(url); try { ByteArrayEntity arrayEntity = new ByteArrayEntity(paramArrayOfByte); arrayEntity.setContentType("application/octet-stream"); httpPost.setEntity(arrayEntity); HttpEntity tempEntity = httpPost.getEntity(); InputStream is = tempEntity.getContent(); StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; int n; while ((n = is.read(b)) != -1) { out.append(new String(b, 0, n)); } String param = out.toString(); System.out.println(param); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT); HttpConnectionParams.setSoTimeout(httpParameters, TIME_OUT); if (isMobileActive(context)) { HttpHost proxy = getHttpProxy(context); if (proxy != null) httpParameters.setIntParameter(proxy.getHostName(), proxy.getPort()); } DefaultHttpClient client = new DefaultHttpClient(httpParameters); HttpResponse response = client.execute(httpPost); int res = response.getStatusLine().getStatusCode(); if (res == 200) { result = EntityUtils.toString(response.getEntity()); } } catch (Exception e) { return " Fail to establish http connection!" + e.getMessage(); } finally { stopHttpPost(httpPostId); httpPost = null; } return result; }