Android GET方式和POST方式提交给WEB服务器

来源:互联网 发布:程序员要出差吗 编辑:程序博客网 时间:2024/05/22 10:49
一、GET方式:
public void testRequestByGET(){try {StringBuffer sb = new StringBuffer();sb.append("http://192.168.241.1:8080/test/servlet/ManageServlet?title='");sb.append(URLEncoder.encode("中国", "UTF-8"));sb.append("'&time=10");URL url = new URL(sb.toString());HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(5000);conn.setRequestMethod("GET");if(conn.getResponseCode() == 200){Log.i(TAG, "success");} else {Log.i(TAG, "fail");}} catch (Exception e) {e.printStackTrace();}}

二、POST方式:

public void save(){try {String path = new String("http://172.30.1.114:8080/test/servlet/ManageServlet");Map<String, String> params = new HashMap<String, String>();params.put("title", "少年时代");params.put("time", String.valueOf(10));// sendPOSTRequest(path, params, "UTF-8");<span style="white-space:pre"></span>sendHttpClientPOSTRequest(path, params, "UTF-8");<span style="white-space:pre"></span>} catch (Exception e) {e.printStackTrace();}}

</pre><pre code_snippet_id="538522" snippet_file_name="blog_20141201_2_5669117" name="code" class="java">private boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{StringBuilder sb = new StringBuilder();if(params != null && !params.isEmpty()){for(Map.Entry<String, String> entry : params.entrySet()){sb.append(entry.getKey()).append("=");sb.append(URLEncoder.encode(entry.getValue(), encoding));// 使用URLENcoder.encode进行编码sb.append("&");}sb.deleteCharAt(sb.length()-1);// 去掉最后一个“&”byte[] entry = sb.toString().getBytes();// 得到实体数据HttpURLConnection conn = (HttpURLConnection)(new URL(path)).openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("POST");conn.setDoOutput(true);// 允许往外输出数据流conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");conn.setRequestProperty("Content-Length", String.valueOf(entry.length));OutputStream outputStream = conn.getOutputStream();outputStream.write(entry);if(conn.getResponseCode() == 200){Log.i(TAG, "success");return true;}}Log.i(TAG, "fail");return false;}

/** * 第二种方法:使用HttpClient发送POST请求 * @return * @throws Exception  */public boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放请求参数StringBuilder sb = new StringBuilder();if(params != null && !params.isEmpty()){for(Map.Entry<String, String> entry : params.entrySet()){pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}}UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding);HttpPost httpPost = new HttpPost(path);httpPost.setEntity(entity);DefaultHttpClient httpClient = new DefaultHttpClient();// DefaultHttpClient:看做浏览器HttpResponse response = httpClient.execute(httpPost);if(response.getStatusLine().getStatusCode() == 200){return true;}return false;}


0 0
原创粉丝点击