热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Eclipse利用HttpClient写post和get连接到后台

文件目录如下:第一个包代码如下:packagecn.itcast.login;importcn.itcast.login.service.DataService;importandroid.ap

文件目录如下:



第一个包代码如下:


package cn.itcast.login;

import cn.itcast.login.service.DataService;
import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts.Data;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DemoActivity extends Activity implements OnClickListener {
 private EditText mEtName;
 private EditText mEtPassword;
 private EditText mEtFilePath;
 private Button mBtLogin;
 private Button mBtLoginPost;
 private Button mBtLoginClientGet;
 private Button mBtLoginClientPost;
 private Button mBtLoginClientPostFile;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mEtName = (EditText) this.findViewById(R.id.et_name);
        mEtPassword = (EditText) this.findViewById(R.id.et_password);
        mBtLogin = (Button) this.findViewById(R.id.bt_login);
        mBtLoginPost = (Button)this.findViewById(R.id.bt_login_post);
        mBtLoginClientGet =  (Button)this.findViewById(R.id.bt_login_client_get);
        mBtLoginClientPostFile =  (Button)this.findViewById(R.id.bt_login_client_post_file);
        mBtLoginClientPost =   (Button)this.findViewById(R.id.bt_login_client_post);
        mEtFilePath = (EditText)this.findViewById(R.id.et_file_path);
        mBtLogin.setOnClickListener(this);
        mBtLoginPost.setOnClickListener(this);
        mBtLoginClientGet.setOnClickListener(this);
        mBtLoginClientPost.setOnClickListener(this);
        mBtLoginClientPostFile.setOnClickListener(this);
    }


 @Override
 public void onClick(View v) {
  String name = mEtName.getText().toString().trim();
  String password = mEtPassword.getText().toString().trim();
  if("".equals(name)||"".equals(password)){
   Toast.makeText(this, "用户名或密码不能为空", 0).show();
   return;
  }
  String path = getResources().getString(R.string.servleturl);
  switch (v.getId()) {
  case R.id.bt_login:

   // 通过get请求 发送数据到服务器
   
   try {
    String result = DataService.sendDataByGet(path, name, password);
    Toast.makeText(this, result, 0).show();
   } catch (Exception e) {
    Toast.makeText(this, "访问网路异常", 0).show();
    e.printStackTrace();
   }
   
   break;
  case R.id.bt_login_post:
   try {
    String result =  DataService.sendDataByPost(path, name, password);
    Toast.makeText(this, result, 0).show();
   } catch (Exception e) {
    Toast.makeText(this, "访问网路异常", 0).show();
    e.printStackTrace();
   }
   break;
  case R.id.bt_login_client_get:
   try {
    String result = DataService.sendDataByHttpClientGet(path, name, password);
    Toast.makeText(this, result, 0).show();
   } catch (Exception e) {
    Toast.makeText(this, "访问网路异常", 0).show();
    e.printStackTrace();
   }
   
   
   break;
  case R.id.bt_login_client_post:
   try {
    String result = DataService.sendDataByHttpClientPost(path, name, password);
    Toast.makeText(this, result, 0).show();
   } catch (Exception e) {
    Toast.makeText(this, "访问网路异常", 0).show();
    e.printStackTrace();
   }
   break; 
  case R.id.bt_login_client_post_file:
   try {
    String filepath = mEtFilePath.getText().toString().trim();
    if("".equals(filepath)){
     Toast.makeText(this, "路径不能为空", 0).show();
     return ;
    }
    String result = DataService.sendDataByHttpClientPost(path, name, password, filepath);
    Toast.makeText(this, result, 0).show();
    System.out.println(new String( result.getBytes("iso8859-1"),"utf-8"));
    
   } catch (Exception e) {
    Toast.makeText(this, "访问网路异常", 0).show();
    e.printStackTrace();
   }
   break; 
  }
  
 }
}




第二个包代码如下:


package cn.itcast.login.service;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import cn.itcast.login.util.StreamTool;

public class DataService {

 /**
  * 通过get请求提交数据到服务器
  *
  * @param path
  *            服务器servlet的地址
  * @param name
  *            用户名
  * @param password
  *            密码
  * @return 服务器返回回来的string数据
  */
 public static String sendDataByGet(String path, String name, String password)
   throws Exception {
  String param1 = URLEncoder.encode(name);
  String param2 = URLEncoder.encode(password);
  URL url = new URL(path + "?name=" + param1 + "&password=" + param2);
  HttpURLConnection cOnn= (HttpURLConnection) url.openConnection();

  conn.setRequestMethod("GET");
  conn.setReadTimeout(5000);
  // 数据并没有发送给服务器
  // 获取服务器返回的流信息
  InputStream is = conn.getInputStream();
  byte[] result = StreamTool.getBytes(is);

  return new String(result);
 }

 // get post
 // get 一次提交的数据数据量比较小 4K 内部其实通过组拼url的方式
 // post 可以提交比较大的数据 form表单的形式 流的方式写到服务器
 /**
  * 采用post的方式 提交数据到服务器
  *
  * @param path
  *            服务器servlet的地址
  * @param name
  *            用户名
  * @param password
  *            密码
  * @return 服务器返回的数据信息
  * @throws Exception
  */
 public static String sendDataByPost(String path, String name,
   String password) throws Exception {
  String param1 = URLEncoder.encode(name);
  String param2 = URLEncoder.encode(password);
  URL url = new URL(path);
  HttpURLConnection cOnn= (HttpURLConnection) url.openConnection();

  String data = "name=" + param1 + "&password=" + param2;

  conn.setRequestMethod("POST");
  conn.setConnectTimeout(5000);
  // 设置 http协议可以向服务器写数据
  conn.setDoOutput(true);
  // 设置http协议的消息头
  conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  conn.setRequestProperty("Content-Length", data.length() + "");
  // 把我们准备好的data数据写给服务器
  OutputStream os = conn.getOutputStream();
  os.write(data.getBytes());
  // httpurlconnection 底层实现 outputstream 是一个缓冲输出流
  // 只要我们获取任何一个服务器返回的信息 , 数据就会被提交给服务器 , 得到服务器返回的流信息
  int code = conn.getResponseCode();
  if (code == 200) {
   InputStream is = conn.getInputStream();
   byte[] result = StreamTool.getBytes(is);
   return new String(result);
  } else {
   throw new IllegalStateException("服务器状态异常");
  }
 }
 
 
 /**
  * httpclient 浏览器的简单包装
  * new HttpClient 就相当于得到了一个浏览器
  */
 public static String sendDataByHttpClientGet (String path , String name,String password) throws Exception{
  
  //1. 获取到一个浏览器的实例
  HttpClient client = new DefaultHttpClient();
  //2. 准备请求的地址
  String param1 = URLEncoder.encode(name);
  String param2 = URLEncoder.encode(password);
  HttpGet httpGet = new HttpGet(path + "?name=" + param1 + "&password=" + param2);
  
  //3. 敲回车 发请求
  HttpResponse  resspOnse= client.execute(httpGet);
  int code = ressponse.getStatusLine().getStatusCode();
  if(code == 200){
   InputStream is  =ressponse.getEntity().getContent();
   byte[] result = StreamTool.getBytes(is);
   return new String(result);
  }
  else{
   throw new IllegalStateException("服务器状态异常");
  }
 }
 
 public static String sendDataByHttpClientPost(String path , String name,String password) throws Exception{
  
  //1. 获取到一个浏览器的实例
  HttpClient client = new DefaultHttpClient();
  //2. 准备要请求的 数据类型
  HttpPost httppost = new HttpPost(path);
  // 键值对
  List parameters = new ArrayList();
  
  parameters.add(new BasicNameValuePair("name", name));
  parameters.add(new BasicNameValuePair("password", password));
  
  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
  
  
  //3.设置post请求的数据实体
  httppost.setEntity(entity);
  
  //4. 发送数据给服务器
  HttpResponse  resspOnse= client.execute(httppost);
  int code = ressponse.getStatusLine().getStatusCode();
  if(code == 200){
   InputStream is  =ressponse.getEntity().getContent();
   byte[] result = StreamTool.getBytes(is);
   return new String(result);
  }
  else{
   throw new IllegalStateException("服务器状态异常");
  }
 }
 
 /**
  * 提交数据给服务器 带一个文件
  * @param path
  * @param name
  * @param password
  * @param filepath 文件在手机上的路径
  *
  * @return
  * @throws Exception
  */
 public  static String sendDataByHttpClientPost(String path , String name,String password ,String filepath) throws Exception{
  // 实例化上传数据的 数组  part []
  Part[] parts = {new StringPart("name", name),
      new StringPart("password", password),
      new FilePart("file", new File(filepath))};
  
  PostMethod filePost = new PostMethod(path);
  
  
  filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
  org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams()
          .setConnectionTimeout(5000);
  int status = client.executeMethod(filePost);
  if(status==200){
   
   System.out.println( filePost.getResponseCharSet());
   String result = new String(filePost.getResponseBodyAsString());
   String ha = new String ( result.getBytes("ISO-8859-1"),"UTF-8");
   System.out.println(ha);
   
   System.out.println("--"+result);
   return result;
  }
  else{
   throw new IllegalStateException("服务器状态异常");
  }
 
 }
}





第三个包代码如下:(第三个包里是一个工具包)


package cn.itcast.login.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

public class StreamTool {
 /**
  * 把一个inputstream里面的内容转化成一个byte[]
  */
 
 public static byte[] getBytes(InputStream is) throws Exception{
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while((len = is.read(buffer))!=-1){
   bos.write(buffer, 0, len);
  }
  is.close();
  bos.flush();
  byte[] result = bos.toByteArray();
  System.out.println(new String(result));
  return  result;
 }
}



推荐阅读
  • 使用 Azure Service Principal 和 Microsoft Graph API 获取 AAD 用户列表
    本文介绍了一段通用代码示例,该代码不仅能够操作 Azure Active Directory (AAD),还可以通过 Azure Service Principal 的授权访问和管理 Azure 订阅资源。Azure 的架构可以分为两个层级:AAD 和 Subscription。 ... [详细]
  • 本文深入探讨了Linux系统中网卡绑定(bonding)的七种工作模式。网卡绑定技术通过将多个物理网卡组合成一个逻辑网卡,实现网络冗余、带宽聚合和负载均衡,在生产环境中广泛应用。文章详细介绍了每种模式的特点、适用场景及配置方法。 ... [详细]
  • 在维护公司项目时,发现按下手机的某个物理按键后会激活相应的服务,并在屏幕上模拟点击特定坐标点。本文详细介绍了如何使用ADB Shell Input命令来模拟各种输入事件,包括滑动、按键和点击等。 ... [详细]
  • 使用Python在SAE上开发新浪微博应用的初步探索
    最近重新审视了新浪云平台(SAE)提供的服务,发现其已支持Python开发。本文将详细介绍如何利用Django框架构建一个简单的新浪微博应用,并分享开发过程中的关键步骤。 ... [详细]
  • 本文由瀚高PG实验室撰写,详细介绍了如何在PostgreSQL中创建、管理和删除模式。文章涵盖了创建模式的基本命令、public模式的特性、权限设置以及通过角色对象简化操作的方法。 ... [详细]
  • Docker的安全基准
    nsitionalENhttp:www.w3.orgTRxhtml1DTDxhtml1-transitional.dtd ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • 本文详细介绍了如何使用PHP检测AJAX请求,通过分析预定义服务器变量来判断请求是否来自XMLHttpRequest。此方法简单实用,适用于各种Web开发场景。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • PHP 5.2.5 安装与配置指南
    本文详细介绍了 PHP 5.2.5 的安装和配置步骤,帮助开发者解决常见的环境配置问题,特别是上传图片时遇到的错误。通过本教程,您可以顺利搭建并优化 PHP 运行环境。 ... [详细]
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 本文探讨了 RESTful API 和传统接口之间的关键差异,解释了为什么 RESTful API 在设计和实现上具有独特的优势。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • MQTT技术周报:硬件连接与协议解析
    本周开发笔记重点介绍了在新项目中使用MQTT协议进行硬件连接的技术细节,涵盖其特性、原理及实现步骤。 ... [详细]
  • 360SRC安全应急响应:从漏洞提交到修复的全过程
    本文详细介绍了360SRC平台处理一起关键安全事件的过程,涵盖从漏洞提交、验证、排查到最终修复的各个环节。通过这一案例,展示了360在安全应急响应方面的专业能力和严谨态度。 ... [详细]
author-avatar
张逸紫惟雨
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有