使用httpclient框架分别用post,get方式提交

package com.example.httpclient;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MyActivity extends Activity {
    private EditText et1;
    private EditText et2;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String result = (String) msg.obj;
                    Toast.makeText(MyActivity.this,result,Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    String o = (String) msg.obj;
                    Toast.makeText(MyActivity.this,o,Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        findViewById(R.id.get).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        String username = et1.getText().toString();
                        String password = et2.getText().toString();
                        String path = "http://192.168.21.1:8080/ok/servlet/Login?username="+username+"&password="+password;
                        //创建HttpClient对象
                        HttpClient httpClient = new DefaultHttpClient();
                        //创建get方法
                        HttpGet httpGet = new HttpGet(path);

                        try {
                            //使用客户端对象用get方式提交到服务器
                            HttpResponse httpResponse = httpClient.execute(httpGet);
                            //得到状态行,这里有响应码等信息
                            StatusLine statusLine = httpResponse.getStatusLine();
                            //得到响应码
                            if(statusLine.getStatusCode()==200){
                                //得到响应的实体,这里有输入输出流信息
                                HttpEntity httpEntity = httpResponse.getEntity();
                                InputStream inputStream = httpEntity.getContent();
                                String data = getDataFromIn(inputStream);
                                Message msg = handler.obtainMessage();
                                msg.what = 1;
                                msg.obj = data;
                                handler.sendMessage(msg);

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            }
        });

        findViewById(R.id.post).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        String username = et1.getText().toString();
                        String password = et2.getText().toString();
                        String path = "http://192.168.21.1:8080/ok/servlet/Login";
                        //创建客户端对象
                        HttpClient httpClient = new DefaultHttpClient();
                        //创建post方法
                        HttpPost httpPost = new HttpPost(path);
                        //声明并实例化list存放basicNameValuePair
                        List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
                        //把要提交的值放到namevaluepair中
                        BasicNameValuePair basicNameValuePair = new BasicNameValuePair("username",username);
                        BasicNameValuePair basicNameValuePair2 = new BasicNameValuePair("password",password);
                        list.add(basicNameValuePair);
                        list.add(basicNameValuePair2);
                        try {
                        //表单提交的实体这个方法需要两个参数一个是list<namevaluepair> 还有一个编码集
                        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list,"utf-8");
                        //设置实体
                        httpPost.setEntity(urlEncodedFormEntity);

                            //客户端对象使用post方式提交
                            HttpResponse httpResponse = httpClient.execute(httpPost);
                            StatusLine statusLine = httpResponse.getStatusLine();
                            if(statusLine.getStatusCode()==200){
                                HttpEntity httpEntity = httpResponse.getEntity();
                                InputStream in = httpEntity.getContent();
                                String ok =  getDataFromIn(in);
                                Message msg = handler.obtainMessage();
                                msg.what = 2;
                                msg.obj =ok;
                                handler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();

            }
        });

    }
    private static String getDataFromIn(InputStream in){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        try {
            while ((len = in.read(b))!=-1){
                out.write(b,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(out.toByteArray());
    }

}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <EditText
            android:id="@+id/et1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入用户名"/>
    <EditText
            android:id="@+id/et2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入密码"/>
    <Button
            android:id="@+id/get"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="get"/>
    <Button
            android:id="@+id/post"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="post"
            />
</LinearLayout>
时间: 2024-10-10 06:07:24

使用httpclient框架分别用post,get方式提交的相关文章

采用Android中的httpclient框架发送get请求

/** * 采用httpclientGet请求的方式 * * @param username * @param password * @return null表示求得的路径有问题,text返回请求得到的数据 */ public static String httpclientGet(String username, String password) { try { // 1.打开一个浏览器 HttpClient client = new DefaultHttpClient(); // 2.输入地

采用Android中的httpclient框架发送post请求

/** * 采用httpclientPost请求的方式 * * @param username * @param password * @return null表示求得的路径有问题,text返回请求得到的数据 */ public static String httpclientPost(String username, String password) { try { // 1.打开一个浏览器 HttpClient client = new DefaultHttpClient(); // 2.输

Android(java)学习笔记213:开源框架post和get方式提交数据(qq登录案例)

1.前面提到Http的get/post方式  . HttpClient方式,实际工作的时候不常用到,因为这些方式编写代码是很麻烦的 2.Android应用会经常使用http协议进行传输,网上会有很完善开源框架,已经包装好了http的get/post,还有httpclient等等:这样我们开发周期也会缩短: 3.下面通过一个Android案例来进行,说明常用的Http框架:  在http://github.com/中搜索async http: 这里发现明显第1个android-async-http

s2sh框架整合详细配置-xml方式

s2sh整合之xml方式 说明:本文档所采用的框架版本为:Struts 2.1.8, Sping2.5.5,  Hibernate 3.5.6 1.    需要的jar包: ------------Strut2-----------: commons-fileupload-1.2.1.jar commons-io-1.3.2.jar commons-logging.jar freemarker-2.3.15.jar ognl-2.7.3.jar struts2-core-2.1.8.1.jar

android 学习随笔十二(网络:使用异步HttpClient框架)

使用异步HttpClient框架发送get.post请求 在https://github.com/ 搜索 asyn-http https://github.com/search?utf8=?&q=asyn-http 下载 loopj/android-async-http public class MainActivity extends Activity { Handler handler = new Handler(){ public void handleMessage(android.os

使用异步httpclient框架做get,post提交数据

1.将异步httpclient框架导入 下载地址:http://download.csdn.net/detail/sinat_32804317/9555641 2.代码实现 1 public class MainActivity extends Activity { 2 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setCont

Laravel框架定时任务2种实现方式示例

本文实例讲述了Laravel框架定时任务2种实现方式.分享给大家供大家参考,具体如下: 第一种 1.生成一个commands文件 > php artisan make:command test 2.打开文件进行修改 laravel\App\Console\Commands\test.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Lo

Android 通过GET和POST方式提交参数给web应用

如何把数据上传到web应用 应用界面: 视频名称:title 时长:timelength 保存,点击保存按钮提交到web应用中,web应用中开发Manageservlet来接收数据. get方式 服务端: public class ManageServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,H

DWZ框架Ajax无刷新表单提交处理流程

DWZ框架Ajax无刷新表单提交处理流程是: 1.       ajax表单提交给服务器 2.       服务器返回一个固定格式json结构 3.       js会调函数根据这个json数据做相应的处理 注意: DWZ框架默认的ajax表单提交都是返回json数据,告诉客户端操作是否成功,成功或失败提示信息,以及成功后的处理方式(刷新某个navTab或关闭某个navTab或navTab页面跳转). 表单提交后服务器操作失败了,客户端接收statusCode和message后给出错误提示,表单