android http 连接
来源:互联网 发布:unity3d摄像机自动缩放 编辑:程序博客网 时间:2024/05/29 15:36
public class HttpClient {public static String sendHttpClientPost(String path,Map<String, String> map, String encode) {List<NameValuePair> list = new ArrayList<NameValuePair>();if (map != null && !map.isEmpty()) {for (Map.Entry<String, String> entry : map.entrySet()) {list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}}try {// 实现将请求的参数封装到表单中,请求体当中UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);// 使用Post方式提交数据HttpPost httpPost = new HttpPost(path);httpPost.setEntity(entity);// 执行Post请求DefaultHttpClient client = new DefaultHttpClient();HttpResponse httpResponse = client.execute(httpPost);if (httpResponse.getStatusLine().getStatusCode() == 200) {httpResponse.getEntity().getContent();return changInputStream(httpResponse.getEntity().getContent(),encode);}else{System.out.println("error");}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "";}public static String changInputStream(InputStream inputStream,String encode) {//将输入流变成字符串ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();byte[] data=new byte[1024];int len=0;String result="";try{if(inputStream!=null){while((len=inputStream.read(data))!=-1){byteArrayOutputStream.write(data,0,len);}}result=new String(byteArrayOutputStream.toByteArray(),encode);}catch(Exception e){}return result;}public static void main(String[] args) {// TODO Auto-generated method stubString path="http://10.118.163.171/http/HttpServlet";Map<String, String> params = new HashMap<String, String>();params.put("name", "admin");params.put("pwd", "199273");String result = sendHttpClientPost(path, params, "utf-8");System.out.println("--result-->" + result);}}