HttpClient用Post请求网络数据

本文介绍了一种使用Android平台下的HttpClient发起POST请求的方法,并详细展示了如何构造请求参数、处理响应数据及解析JSON的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.httpclient_post1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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;

import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

import com.example.model.One;
import com.google.gson.Gson;

/**
 * 用HttpClient的post方法请求网络数据
 *
 */

public class MainActivity extends Activity 
{
	//定义成员变量
	private TextView tv;
	private List<NameValuePair> list;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		init();
	}
	
	public void init()
	{
		//找对象
		tv=(TextView) super.findViewById(R.id.tv);
		
//		new Thread(){
//			@Override
//			public void run() {
//				super.run();
//				
//				HttpClient hc=new DefaultHttpClient();	//创建HttpClient对象
//				HttpPost hp=new HttpPost("http://japi.juhe.cn/calendar/day?date=2015-1-1");	//创建HttpPsot对象
//				
//				//创建参数对列
//				list=new ArrayList<NameValuePair>();
//				list.add(new BasicNameValuePair("key", "49c81856de2815392ff33d3b271734db"));
//
				String cy=URLEncoder.encode("画蛇添足", "UTF-8");	//转换文字字符集
//				
//				try {
//					UrlEncodedFormEntity urlentity=new UrlEncodedFormEntity(list , HTTP.UTF_8);	//创建UrlEncodedFormEntity对象,设置文字字符集(把接口和键转换成url编码形式)
//					hp.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");	//设置乱码(键值由自己填实用)
//					hp.setEntity(urlentity);	//设置请求参数
//					HttpResponse hr=hc.execute(hp); 	//发送post请求,返回HttpResponse
//					
//					if(hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK)	//判断请求是否成功。   getStatusLine()获取此响应的状态行;getStatusCode()获取响应
//					{
//						InputStream is=hr.getEntity().getContent();	//获取输入流       getEntity()获取HttpEntity对象(该对象包装了服务器的响应内容);getContent()获取相应内容
//						InputStreamReader isr=new InputStreamReader(is);	//转换字符输入流
//						BufferedReader br=new BufferedReader(isr);	//接管道输入流
//						String strJson=null;
//						StringBuffer sb=new StringBuffer();
//						while((strJson=br.readLine()) != null)
//						{
//							sb.append(strJson);	//拼接字符串
//						}
//						Message msg=h.obtainMessage(1, sb.toString());
//						h.sendMessage(msg);
//					}
//				} catch (UnsupportedEncodingException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (ClientProtocolException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}.start();
		
//		new Thread(){
//			@Override
//			public void run() {
//				super.run();
//				
//				HttpClient hc=new DefaultHttpClient();	//获取HttpClient对象
//				HttpPost hp=new HttpPost("http://api2.juheapi.com/video/query");	//创建HTTpPost对象
//				
//				//创建参数队列
//				list=new ArrayList<NameValuePair>();
//				list.add(new BasicNameValuePair("kw", "闪电侠"));
//				list.add(new BasicNameValuePair("key", "8458469fd3b71a26b05721b65f851d26"));
				list.add(new BasicNameValuePair("cat", "1"));
//				
//				try {
//					UrlEncodedFormEntity urlEntity=new UrlEncodedFormEntity(list, "UTF-8");	//创建UrlEncodedFormEntity对象,把参数转换成url实体,设置文字字符集
//					hp.setEntity(urlEntity);	//设置请求参数
//					
//					HttpResponse hr=hc.execute(hp); 	//客服端用post方法发送请求,获取服务器响应的HttpResponse
//					if(hr.getStatusLine().getStatusCode()==HttpStatus.SC_OK)	//判断请求是否成功    getStatusLine()获取此响应队列;getStatusCode()获取相应码
//					{
//						InputStream is=hr.getEntity().getContent();	//获取输入流      getEntity()获取HttpEntity对象(该对象包装了服务器响应的内容);getContent()获取响应内容
//						BufferedReader br=new BufferedReader(new InputStreamReader(is));	//接字符管道输入流
//						String strJson=null;
//						StringBuffer sb=new StringBuffer();
//						while((strJson=br.readLine()) != null)
//						{
//							sb.append(strJson);
//						}
//						
//						Gson g=new Gson();
//						One one=g.fromJson(sb.toString(), One.class);
//						Log.i("TAG", "解析的数据是:"+one.toString()+one.param.key+one.param.kw+one.result);
//						Message msg=h.obtainMessage(1, sb.toString());
//						h.sendMessage(msg);
//						hc.getConnectionManager().shutdown();	//释放连接
//					}
//				} catch (UnsupportedEncodingException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (ClientProtocolException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				
//			}
//		}.start();
		
		new Thread(){
			@Override
			public void run() {
				super.run();
				
				HttpClient hc=new DefaultHttpClient();
				HttpPost hp=new HttpPost("http://api2.juheapi.com/video/query");
				
				list=new ArrayList<NameValuePair>();
				list.add(new BasicNameValuePair("kw", "闪电侠"));
				list.add(new BasicNameValuePair("key", "8458469fd3b71a26b05721b65f851d26"));
				UrlEncodedFormEntity urlEntity;
				try {
					urlEntity = new UrlEncodedFormEntity(list, "UTF-8");
					hp.setEntity(urlEntity);
					
					HttpResponse hr=hc.execute(hp);
					if(hr.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
					{
						InputStream is=hr.getEntity().getContent();
						BufferedReader br=new BufferedReader(new InputStreamReader(is));
						String strJson=null;
						StringBuffer sb=new StringBuffer();
						while((strJson=br.readLine()) != null)
						{
							sb.append(strJson);
						}
						
						Gson g=new Gson();
						One one=g.fromJson(sb.toString(), One.class);
						Log.i("TAG", "解析的数据是:"+one.toString()+one.param.key+one.param.kw+one.result);
						Message msg=h.obtainMessage(1, sb.toString());
						h.sendMessage(msg);
						hc.getConnectionManager().shutdown();	//释放连接
					}
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}	
			}
		}.start();
	}
	
	Handler h=new Handler(){
		public void handleMessage(android.os.Message msg) {
			if(msg.what==1)
			{
				String s=(String) msg.obj;
				tv.setText(s);
			}
		};
	};
	
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值