HttpClient 实现POST请求
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpClient 实现POST请求相关的知识,希望对你有一定的参考价值。
String httpUrl = "http://192.168.1.110:8080/httpget.jsp"; /* * NameValuePair代表一个HEADER,List<NameValuePair>存储全部的头字段 * UrlEncodedFormEntity类似于URLEncoder语句进行URL编码 * HttpPost类似于HTTP的POST请求 * client.execute()类似于发出请求,并返回Response */ // HttpPost连接对象 HttpPost httpRequest = new HttpPost(httpUrl); // 使用NameValuePair来保存要传递的Post参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); // 添加要传递的参数 NameValuePair pair1 = new BasicNameValuePair("par", "HttpClient_android_Post")); params.add(pair1); //params.add(new BasicNameValuePair("par", "HttpClient_android_Post")); try { // 设置字符集 HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312"); // 请求httpRequest httpRequest.setEntity(httpentity); // 取得默认的HttpClient HttpClient httpclient = new DefaultHttpClient(); // 取得HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // HttpStatus.SC_OK表示连接成功 if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 取得返回的字符串 String strResult = EntityUtils.toString(httpResponse.getEntity()); mTextView.setText(strResult); } else { mTextView.setText("请求错误!"); } } catch (ClientProtocolException e) { mTextView.setText(e.getMessage().toString()); } catch (IOException e) { mTextView.setText(e.getMessage().toString()); } catch (Exception e){ mTextView.setText(e.getMessage().toString()); }
以上是关于HttpClient 实现POST请求的主要内容,如果未能解决你的问题,请参考以下文章
C#用HttpClient类post get,怎么设置cookies