热门标签 | 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;
 }
}



推荐阅读
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讲述了如何通过代码在Android中更改Recycler视图项的背景颜色。通过在onBindViewHolder方法中设置条件判断,可以实现根据条件改变背景颜色的效果。同时,还介绍了如何修改底部边框颜色以及提供了RecyclerView Fragment layout.xml和项目布局文件的示例代码。 ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • vue使用
    关键词: ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Android实战——jsoup实现网络爬虫,糗事百科项目的起步
    本文介绍了Android实战中使用jsoup实现网络爬虫的方法,以糗事百科项目为例。对于初学者来说,数据源的缺乏是做项目的最大烦恼之一。本文讲述了如何使用网络爬虫获取数据,并以糗事百科作为练手项目。同时,提到了使用jsoup需要结合前端基础知识,以及如果学过JS的话可以更轻松地使用该框架。 ... [详细]
  • 在IDEA中运行CAS服务器的配置方法
    本文介绍了在IDEA中运行CAS服务器的配置方法,包括下载CAS模板Overlay Template、解压并添加项目、配置tomcat、运行CAS服务器等步骤。通过本文的指导,读者可以轻松在IDEA中进行CAS服务器的运行和配置。 ... [详细]
  • 1Lock与ReadWriteLock1.1LockpublicinterfaceLock{voidlock();voidlockInterruptibl ... [详细]
  • 本文介绍了如何使用MATLAB调用摄像头进行人脸检测和识别。首先需要安装扩展工具,并下载安装OS Generic Video Interface。然后使用MATLAB的机器视觉工具箱中的VJ算法进行人脸检测,可以直接调用CascadeObjectDetector函数进行检测。同时还介绍了如何调用摄像头进行人脸识别,并对每一帧图像进行识别。最后,给出了一些相关的参考资料和实例。 ... [详细]
  • 一面自我介绍对象相等的判断,equals方法实现。可以简单描述挫折,并说明自己如何克服,最终有哪些收获。职业规划表明自己决心,首先自己不准备继续求学了,必须招工作了。希望去哪 ... [详细]
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社区 版权所有