在android sdk22以下版本测试通过
使用的如下jar包:
1、httpcore-4.3.3.jar
2、httpmime-4.3.6.jar
package com.zh.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.InetAddress; import java.net.Socket; import java.net.URL; import java.nio.charset.Charset; 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.NameValuePair; import org.apache.http.client.ClientProtocolException; 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.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; public class SimpleClient { private static HttpClient httpClient; private static String JSESSIONID; //定义一个静态的字段,保存sessionID public static String ip; public static int port; public static String realPath; static{ httpClient=new DefaultHttpClient(); } @SuppressWarnings("rawtypes") public static String doGet(String url, Map params) throws Exception { /* 建立HTTPGet对象 */ StringBuffer strUrl=new StringBuffer("http://"+ip+":"+port+"/"); strUrl.append(url); String paramStr = ""; if (params != null) { Iterator iter = params.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); paramStr += paramStr = "&" + key + "=" + val; } } if (!paramStr.equals("")) { paramStr = paramStr.replaceFirst("&", "?"); strUrl.append(paramStr); } HttpGet httpRequest = new HttpGet(strUrl.toString()); httpRequest.setHeader("Charset", "utf-8"); String strResult = "doGetError"; /* 发送请求并等待响应 */ HttpResponse httpResponse = httpClient.execute(httpRequest); /* 若状态码为200 ok */ if (httpResponse.getStatusLine().getStatusCode() == 200) { /* 读返回数据 */ strResult = EntityUtils.toString(httpResponse.getEntity()); } else { strResult = "Error Response: " + httpResponse.getStatusLine().toString(); } Log.v("strResult", strResult); return strResult; } public static String doPost(String url, List<NameValuePair> params) throws Exception { /* 建立HTTPPost对象 */ StringBuffer strUrl=new StringBuffer("http://"+ip+":"+port+"/"); strUrl.append(url); Log.i("doPost", strUrl.toString()); HttpPost httpRequest = new HttpPost(strUrl.toString()); httpRequest.setHeader("Charset", "utf-8"); String strResult = "doPostError"; /* 添加请求参数到请求对象 */ if (params != null && params.size() > 0) { httpRequest.setEntity(new UrlEncodedFormEntity(params, "utf-8")); } if(null != JSESSIONID){ httpRequest.setHeader("Cookie", "JSESSIONID="+JSESSIONID); } /* 发送请求并等待响应 */ HttpResponse httpResponse = httpClient.execute(httpRequest); /* 若状态码为200 ok */ if (httpResponse.getStatusLine().getStatusCode() == 200) { /* 读返回数据 */ strResult = EntityUtils.toString(httpResponse.getEntity()); /* 获取cookieStore */ /*CookieStore cookieStore = httpClient.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(int i=0;i<cookies.size();i++){ if("JSESSIONID".equals(cookies.get(i).getName())){ JSESSIONID = cookies.get(i).getValue(); break; } } */ } Log.v("strResult", strResult); return strResult; } public static String doPost(String url, Map<String, String> params,File file) throws Exception { /* 建立HTTPPost对象 */ StringBuffer strUrl=new StringBuffer("http://"+ip+":"+port+"/"); strUrl.append(url); HttpPost httpRequest = new HttpPost(strUrl.toString()); httpRequest.setHeader("Charset", "utf-8"); String strResult = "doPostError"; /* 添加请求参数到请求对象 */ ContentType contentType= ContentType.create("text/plain", "utf-8"); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("UTF-8"));//设置请求的编码格式 builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式 if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { StringBody par = new StringBody(entry.getValue(),contentType); builder.addPart(entry.getKey(), par); } } //FileBody uploadfile=new FileBody(file); InputStreamBody uploadfile=new InputStreamBody(new FileInputStream(file),file.getName()); builder.addPart("myUpload", uploadfile); HttpEntity entity = builder.build();// 生成 HTTP POST 实体 httpRequest.setEntity(entity); if(null != JSESSIONID){ httpRequest.setHeader("Cookie", "JSESSIONID="+JSESSIONID); } /* 发送请求并等待响应 */ HttpResponse httpResponse = httpClient.execute(httpRequest); /* 若状态码为200 ok */ if (httpResponse.getStatusLine().getStatusCode() == 200) { /* 读返回数据 */ strResult = EntityUtils.toString(httpResponse.getEntity()); /* 获取cookieStore */ /*CookieStore cookieStore = httpClient.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(int i=0;i<cookies.size();i++){ if("JSESSIONID".equals(cookies.get(i).getName())){ JSESSIONID = cookies.get(i).getValue(); break; } } */ } return strResult; } public static Bitmap getCodeImage(String path){ StringBuffer CodeImageUrl = new StringBuffer("http://"+ip+":"+port); if(path!=null&&!path.equals("")){ CodeImageUrl.append("/"+path); } CodeImageUrl.append("/imgCode?rnd="+Math.random()); HttpGet httpRequest=new HttpGet(CodeImageUrl.toString()); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpRequest); } catch (ClientProtocolException e) { // TODO Auto-generated catch block Log.i("abc1",e.toString()); } catch (IOException e) { // TODO Auto-generated catch block Log.i("abc2",e.toString()); } if(httpResponse==null){ return null; } if(httpResponse.getStatusLine().getStatusCode()==200) { byte[] data = null; try { data = EntityUtils.toByteArray(httpResponse.getEntity()); } catch (IOException e) { // TODO Auto-generated catch block Log.i("abc3",e.toString()); } Bitmap bitmap=null; if(data!=null){ bitmap=BitmapFactory.decodeByteArray(data, 0, data.length); Log.i("width:"+bitmap.getWidth()+" height:", bitmap.getHeight()+""); } return bitmap; }else{ return null; } } }
注意:本文归作者所有,未经作者允许,不得转载