Android学习笔记(六)之post请求

目前经常会使用的手机客户端去请求服务器

下面用两种方法

第一种:

是类似于直接请求访问url

代码如下:

package com.jouhu.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AssignService {

	
	public static String getServiceName(String assignUrl){
		String name=null;
		try {
			URL url = new URL(assignUrl);
			URLConnection uc =  url.openConnection();
			uc.setConnectTimeout(5000);
			uc.setReadTimeout(8000);
			InputStream in = uc.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			name = br.readLine();
			br.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return name;
	}
	
	public static void main(String[] arg) throws InterruptedException{
		final String URL_ASSIGN = "http://192.168.1.192:8888/ServiceAssign/assignService.action";
		int num=500;
		final CountDownLatch begin = new CountDownLatch(1);
		final CountDownLatch end = new CountDownLatch(num);
		final ExecutorService exec = Executors.newFixedThreadPool(num);
		for (int index = 0; index < num; index++) {
			Runnable run = new Runnable() {
				public void run() {
					try {
						begin.await();
						AssignService.getServiceName(URL_ASSIGN);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						end.countDown();
					}
				}
			};
			exec.submit(run);
		}
		System.out.println("Start");
		begin.countDown();
		end.await();
		exec.shutdown();
		System.out.println("Over");
	}
}


第二种:

通过POST将本地数据发送给服务器,string参数表

/**
 * GpsPoiService.java
 * 版权所有(C) 2012 
 * 创建:cuiran 2012-9-12 下午2:49:25
 */
package com.jouhu.service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.jouhu.util.AssignService;
import com.jouhu.util.BaseNameValuePair;
import com.jouhu.util.Conf;

/**
 * TODO
 * @author cuiran
 * @version TODO
 */
public class GpsPoiService {
	
	private String url="http://219.143.94.189:8405/fastweb/fastweb.do?m=addgps";//服务地址
	
	public String sendMsg(double x,double y,String address) {
		//URLEncoder.encode(address, "gbk")
		String re="";
		
		try{
			List<NameValuePair> datas = new ArrayList<NameValuePair>();
			datas.add(new BaseNameValuePair("x", ""+x));
			datas.add(new BaseNameValuePair("y", ""+y));
			datas.add(new BaseNameValuePair("address", ""+address));

			re=sendDataByPost(url, datas);
//				StringBuffer str = new StringBuffer();			
//				str.append(url)
//				   .append("&x=")
//				   .append(x)
//				    .append("&y=")
//				   .append(y)
//				   .append("&address=")
//				   .append(URLEncoder.encode(address, "gbk"));
//					Log.i(Conf.TAG, str.toString());
//				 re = AssignService.getServiceName(str.toString());
				
		}catch(Exception e){
			 Log.i(Conf.TAG, "-------"+e.getLocalizedMessage());   
		}
		
		Log.i(Conf.TAG, re);
		return re;
		
	}
	
	// 通过POST将本地数据发送给服务器,string参数表

	public static String sendDataByPost(String url, List<NameValuePair> datas){

	org.apache.http.client.HttpClient client = new DefaultHttpClient();

	HttpPost post = new HttpPost(url);

	HttpResponse resp = null;

	String result = "";

	// post data
	
		try {
	
		post.setEntity(new UrlEncodedFormEntity(datas,HTTP.UTF_8));
	
		resp = client.execute(post);
	
		result = EntityUtils.toString(resp.getEntity());
	
		} catch (UnsupportedEncodingException e) {
	
		e.printStackTrace();
	
		} catch (ClientProtocolException e) {
	
		e.printStackTrace();
	
		} catch (IOException e) {
	
		e.printStackTrace();
	
		}

		return result;

	}

	
	
}


但是在使用第一种情况下,后台服务接收的中文会乱码,具体解决详见:

http://blog.csdn.net/cuiran/article/details/7963553

使用第二种常用的编码是UTF-8,所以后台服务器也需要用该编码接收参数。

 

最后,是给大家分享一个学习Android不错的视频:

老罗Android开发视频教程录制计划

http://www.apkbus.com/android-68413-1-1.html 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cuiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值