HttpUrlConnection Post提交数据到服务器、并得到服务器返回的数据

  1.   
  2. public class HttpUtils {  
  3.     private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 服务端地址  
  4.     private static URL url;  
  5.   
  6.     public HttpUtils() {  
  7.         super();  
  8.     }  
  9.   
  10.     // 静态代码块实例化url  
  11.     static {  
  12.         try {  
  13.             url = new URL(PATH);  
  14.         } catch (MalformedURLException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.   
  19.     /**  
  20.      * 发送消息体到服务端  
  21.      *   
  22.      * @param params  
  23.      * @param encode  
  24.      * @return  
  25.      */  
  26.     public static String sendPostMessage(Map<String, String> params,  
  27.             String encode) {  
  28.         StringBuilder stringBuilder = new StringBuilder();  
  29.         if (params != null && !params.isEmpty()) {  
  30.             for (Map.Entry<String, String> entry : params.entrySet()) {  
  31.                 try {  
  32.                     stringBuilder  
  33.                             .append(entry.getKey())  
  34.                             .append("=")  
  35.                             .append(URLEncoder.encode(entry.getValue(), encode))  
  36.                             .append("&");  
  37.                 } catch (UnsupportedEncodingException e) {  
  38.                     e.printStackTrace();  
  39.                 }  
  40.             }  
  41.             stringBuilder.deleteCharAt(stringBuilder.length() - 1);  
  42.             try {  
  43.                 HttpURLConnection urlConnection = (HttpURLConnection) url  
  44.                         .openConnection();  
  45.                 urlConnection.setConnectTimeout(3000);  
  46.                 urlConnection.setRequestMethod("POST"); // 以post请求方式提交  
  47.                 urlConnection.setDoInput(true); // 读取数据  
  48.                 urlConnection.setDoOutput(true); // 向服务器写数据  
  49.                 // 获取上传信息的大小和长度  
  50.                 byte[] myData = stringBuilder.toString().getBytes();  
  51.                 // 设置请求体的类型是文本类型,表示当前提交的是文本数据  
  52.                 urlConnection.setRequestProperty("Content-Type",  
  53.                         "application/x-www-form-urlencoded");  
  54.                 urlConnection.setRequestProperty("Content-Length",  
  55.                         String.valueOf(myData.length));  
  56.                 // 获得输出流,向服务器输出内容  
  57.                 OutputStream outputStream = urlConnection.getOutputStream();  
  58.                 // 写入数据  
  59.                 outputStream.write(myData, 0, myData.length);  
  60.                 outputStream.close();  
  61.                 // 获得服务器响应结果和状态码  
  62.                 int responseCode = urlConnection.getResponseCode();  
  63.                 if (responseCode == 200) {  
  64.                     // 取回响应的结果  
  65.                     return changeInputStream(urlConnection.getInputStream(),  
  66.                             encode);  
  67.                 }  
  68.             } catch (IOException e) {  
  69.                 e.printStackTrace();  
  70.             }  
  71.   
  72.         }  
  73.         return "";  
  74.     }  
  75.   
  76.     /**  
  77.      * 将一个输入流转换成指定编码的字符串  
  78.      *   
  79.      * @param inputStream  
  80.      * @param encode  
  81.      * @return  
  82.      */  
  83.     private static String changeInputStream(InputStream inputStream,  
  84.             String encode) {  
  85.   
  86.         // 内存流  
  87.         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
  88.         byte[] data = new byte[1024];  
  89.         int len = 0;  
  90.         String result = null;  
  91.         if (inputStream != null) {  
  92.             try {  
  93.                 while ((len = inputStream.read(data)) != -1) {  
  94.                     byteArrayOutputStream.write(data, 0, len);  
  95.                 }  
  96.                 result = new String(byteArrayOutputStream.toByteArray(), encode);  
  97.             } catch (IOException e) {  
  98.                 e.printStackTrace();  
  99.             }  
  100.         }  
  101.         return result;  
  102.     }  
  103.   
  104.     /**  
  105.      * @param args  
  106.      */  
  107.     public static void main(String[] args) {  
  108.         Map<String, String> map = new HashMap<String, String>();  
  109.         map.put("username", "admin");  
  110.         map.put("password", "123456");  
  111.         String result = sendPostMessage(map, "UTF-8");  
  112.         System.out.println(">>>" + result);  
  113.     }  
  114.   
  115. }  



我们再创建一个服务端工程,一个web project,这里创建一个myhttp的工程,先给它创建一个servlet,用来接收参数访问。

创建的servlet配置如下:

[html]  view plain copy
  1. <servlet>  
  2.         <description>This is the description of my J2EE component</description>  
  3.         <display-name>This is the display name of my J2EE component</display-name>  
  4.         <servlet-name>LoginAction</servlet-name>  
  5.         <servlet-class>com.login.manager.LoginAction</servlet-class>  
  6.     </servlet>  
  7.   
  8.     <servlet-mapping>  
  9.         <servlet-name>LoginAction</servlet-name>  
  10.         <url-pattern>/servlet/LoginAction</url-pattern>  
  11.     </servlet-mapping>  


建立的LoginAction.java类继承HttpServlet:

[html]  view plain copy
  1. package com.login.manager;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class LoginAction extends HttpServlet {  
  12.   
  13.     /**  
  14.      * Constructor of the object.  
  15.      */  
  16.     public LoginAction() {  
  17.         super();  
  18.     }  
  19.   
  20.     /**  
  21.      * Destruction of the servlet. <br>  
  22.      */  
  23.     public void destroy() {  
  24.         super.destroy(); // Just puts "destroy" string in log  
  25.         // Put your code here  
  26.     }  
  27.   
  28.     /**  
  29.      * The doGet method of the servlet. <br>  
  30.      *  
  31.      * This method is called when a form has its tag value method equals to get.  
  32.      *   
  33.      * @param request the request send by the client to the server  
  34.      * @param response the response send by the server to the client  
  35.      * @throws ServletException if an error occurred  
  36.      * @throws IOException if an error occurred  
  37.      */  
  38.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  39.             throws ServletException, IOException {  
  40.             this.doPost(request, response);  
  41.     }  
  42.   
  43.     /**  
  44.      * The doPost method of the servlet. <br>  
  45.      *  
  46.      * This method is called when a form has its tag value method equals to post.  
  47.      *   
  48.      * @param request the request send by the client to the server  
  49.      * @param response the response send by the server to the client  
  50.      * @throws ServletException if an error occurred  
  51.      * @throws IOException if an error occurred  
  52.      */  
  53.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  54.             throws ServletException, IOException {  
  55.   
  56.         response.setContentType("text/html;charset=utf-8");  
  57.         request.setCharacterEncoding("utf-8");  
  58.         response.setCharacterEncoding("utf-8");  
  59.         PrintWriter out = response.getWriter();  
  60.         String userName = request.getParameter("username");  
  61.         String passWord = request.getParameter("password");  
  62.         System.out.println("userName:"+userName);  
  63.         System.out.println("passWord:"+passWord);  
  64.         if(userName.equals("admin") && passWord.equals("123456")){ 
  65.                //返回给android客户端的值就是login successful!
  66.             out.print("login successful!");  
  67.         }else{  
  68.             out.print("login failed");  
  69.         }  
  70.         out.flush();  
  71.         out.close();  
  72.     }  
  73.   
  74.     /**  
  75.      * Initialization of the servlet. <br>  
  76.      *  
  77.      * @throws ServletException if an error occurs  
  78.      */  
  79.     public void init() throws ServletException {  
  80.         // Put your code here  
  81.     }  
  82.   
  83. }  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
第一种方法 使用标准的JAVA接口 1 将用户名和密码等用Map泛型封装 再使用StringBuffer 转换成一串字符串 然后新建URL打开openConnection 得到 httpURLConnection 设置最长连接时间和setRequestMethod请求方法 用GET还是POST 提交数据POST 打开输入和输出流 获取上传信息 字节大小以及长度 设置请求体的类型是文本类型 获得输出流 向服务器输出数据 获得服务器响应的结果和状态码 如果 返回码等于200 得到服务器返回的输入流 将输入流转换成指定编码的字符串并返回 就可以成功提交得到服务器返回的信息 第二种方法 使用标准Apache接口 02 03 15 19 30 + 06 12 02 03 15 19 30 31 + 06 12 1 将用户名和密码等用Map泛型封装 再使用List<NameValuePair> list new ArrayList<NameValuePair> ; 转换成一串字符串 然后新建URL打开openConnection 得到 httpURLConnection 设置最长连接时间和setRequestMethod请求方法 用GET还是POST 提交数据POST 打开输入和输出流 获取上传信息 字节大小以及长度 设置请求体的类型是文本类型 获得输出流 向服务器输出数据 获得服务器响应的结果和状态码 如果 返回码等于200 得到服务器返回的输入流 将输入流转换成指定编码的字符串并返回 就可以成功提交得到服务器返回的信息">第一种方法 使用标准的JAVA接口 1 将用户名和密码等用Map泛型封装 再使用StringBuffer 转换成一串字符串 然后新建URL打开openConnection 得到 httpURLConnection 设置最长连接时间和setRequestMethod请求方法 用GET还是POST 提交数据POST [更多]
好的,下面是使用HttpURLConnection进行POST请求,并解析返回结果的Java代码,附有详细解释: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class PostRequest { public static void main(String[] args) { try { // 要发送POST请求的URL String url = "http://localhost:8080/example"; // 设置请求参数 String param = "name=" + URLEncoder.encode("张三", "UTF-8") + "&age=" + URLEncoder.encode("18", "UTF-8"); // 创建URL对象 URL obj = new URL(url); // 创建HttpURLConnection对象 HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为POST con.setRequestMethod("POST"); // 设置请求头信息 con.setRequestProperty("User-Agent", "Mozilla/5.0"); // 设置请求参数类型为表单格式 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 启用输出流,因为POST请求需要向服务器发送数据 con.setDoOutput(true); // 将请求参数写入输出流 DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(param); wr.flush(); wr.close(); // 获取服务器响应的状态码 int responseCode = con.getResponseCode(); // 打印响应状态码 System.out.println("Response Code : " + responseCode); // 读取服务器的响应结果 BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印服务器响应结果 System.out.println(response.toString()); } catch (Exception e) { System.out.println(e.getMessage()); } } } ``` 代码解释: 1. 在第7行,我们定义了要发送POST请求的URL。这里使用了本地服务器地址,实际应用中需要替换成实际的URL。 2. 在第10-12行,我们设置了请求参数。这里只有两个参数:name和age,实际应用中可能需要更多的参数,可以根据实际需求进行修改。 3. 在第15行,我们创建了一个URL对象,用于连接到指定的URL。 4. 在第18行,我们创建了一个HttpURLConnection对象,用于发送POST请求。 5. 在第21-22行,我们设置了请求方法为POST,并添加了一个User-Agent头信息,模拟浏览器请求。 6. 在第25行,我们设置了请求参数类型为表单格式。 7. 在第28行,我们启用了输出流,因为POST请求需要向服务器发送数据。 8. 在第31-33行,我们将请求参数写入输出流,然后关闭输出流。 9. 在第36行,我们获取了服务器响应的状态码,可以用来判断请求是否成功。 10. 在第39-43行,我们读取服务器的响应结果,使用了一个BufferedReader对象逐行读取响应内容,最后将响应内容保存在一个StringBuffer对象中。 11. 在第46行,我们打印了服务器响应结果。 12. 在异常处理块中,我们输出了异常信息,方便调试。 这就是使用HttpURLConnection进行POST请求,并解析返回结果的Java代码,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值