android http 连接
2013-06-05 21:24
204 查看
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 block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.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 stub String 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); } }
相关文章推荐
- eclipse配置SDK时一直出现连接不上http://dl-ssl.google.com/android/eclipse/
- Android网络编程(http连接、xml和json解析)
- Android网络连接之HttpURLConnection和HttpClient
- Android进阶2之Http连接GET/POST请求
- Android网络连接,HttpsURLConnection还是ApacheHTTPClient?
- Android—Http连接之GET/POST请求
- Android—Http连接之GET/POST请求
- Androidの网络Http之判断是否连接服务器
- Android进阶2之Http连接GET/POST请求
- Android网络连接之HttpURLConnection和HttpClient
- Android开发-----关于解决Retrofit打印HttpLog和设置连接超时的问题
- android使用HttpURLConnection连接java ee服务器传输对象
- android异步网络连接开源:Android Asynchronous Http Client
- Android网络连接的两种方法:apache client和httpurlconnection的比较
- 简单的android http连接
- Android—Http连接之GET/POST请求
- 如何设置android HttpPost 连接服务器超时
- 基于Google Volley的Android Http连接库
- Android开发 http和https连接
- Android Http连接和TCP连接的区别