http——post

来源:互联网 发布:vmware osx优化 编辑:程序博客网 时间:2024/06/06 04:46

服务器端:


servlet配置:

  <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>LoginAction</servlet-name>    <servlet-class>com.login.manager.LoginAction</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginAction</servlet-name>    <url-pattern>/servlet/LoginAction</url-pattern>  </servlet-mapping>

在程序中调用该对象:

1

<%String path = request.getContextPath();%>

2

<form name="form1"  method="post" action="<%=path %>/servlet/LoginAction">

注意:此处为URL的路径

3 程序中必要的编码设置

response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");
4 获得参数的一般方法

PrintWriter out = response.getWriter();String username = request.getParameter("username");System.out.println("-username->>"+username);String pswd = request.getParameter("password");System.out.println("-password->>"+pswd);if(username.equals("admin")&&pswd.equals("123")){out.print("login is success!!!!");}else{out.print("login is fail!!!");}out.flush();out.close();


客户端:

方法一:使用java自带的包来处理

package com.http.post;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;public class HttpUtils {// 请求服务器端的urlprivate static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";private static URL url;public HttpUtils() {// TODO Auto-generated constructor stub}static {try {url = new URL(PATH);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * @param params *            填写的url的参数 * @param encode *            字节编码 * @return */public static String sendPostMessage(Map<String, String> params,String encode) {// 作为StringBuffer初始化的字符串StringBuffer buffer = new StringBuffer();try {if (params != null && !params.isEmpty()) {  for (Map.Entry<String, String> entry : params.entrySet()) {// 完成转码操作buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");}buffer.deleteCharAt(buffer.length() - 1);}// System.out.println(buffer.toString());// 删除掉最有一个&System.out.println("-->>"+buffer.toString());HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();urlConnection.setConnectTimeout(3000);urlConnection.setRequestMethod("POST");urlConnection.setDoInput(true);// 表示从服务器获取数据urlConnection.setDoOutput(true);// 表示向服务器写数据// 获得上传信息的字节大小以及长度byte[] mydata = buffer.toString().getBytes();// 表示设置请求体的类型是文本类型urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");urlConnection.setRequestProperty("Content-Length",String.valueOf(mydata.length));// 获得输出流,向服务器输出数据OutputStream outputStream = urlConnection.getOutputStream();outputStream.write(mydata,0,mydata.length);outputStream.close();// 获得服务器响应的结果和状态码int responseCode = urlConnection.getResponseCode();if (responseCode == 200) {return changeInputStream(urlConnection.getInputStream(), encode);}} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "";}/** * 将一个输入流转换成指定编码的字符串 *  * @param inputStream * @param encode * @return */private static String changeInputStream(InputStream inputStream,String encode) {// TODO Auto-generated method stubByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;String result = "";if (inputStream != null) {try {while ((len = inputStream.read(data)) != -1) {outputStream.write(data, 0, len);}result = new String(outputStream.toByteArray(), encode);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMap<String, String> params = new HashMap<String, String>();params.put("username", "admin");params.put("password", "123");String result = HttpUtils.sendPostMessage(params, "utf-8");System.out.println("--result->>" + result);}}


方法二:使用apache的包来处理HTTP

http://blog.csdn.net/javavenus/article/details/6560997

引入的包:


package com.http.post;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;public class HttpUtils {public HttpUtils() {// TODO Auto-generated constructor stub}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) {return changeInputStream(httpResponse.getEntity().getContent(),encode);}} 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 "";}/** * 将一个输入流转换成指定编码的字符串 *  * @param inputStream * @param encode * @return */public static String changeInputStream(InputStream inputStream,String encode) {// TODO Auto-generated method stubByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;String result = "";if (inputStream != null) {try {while ((len = inputStream.read(data)) != -1) {outputStream.write(data, 0, len);}result = new String(outputStream.toByteArray(), encode);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubString path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";Map<String, String> params = new HashMap<String, String>();params.put("username", "admin");params.put("password", "123");String result = HttpUtils.sendHttpClientPost(path, params, "utf-8");System.out.println("-->>"+result);}}


0 0
原创粉丝点击