Android学习笔记(六)之post请求
下面用两种方法
第一种:
是类似于直接请求访问url
代码如下:
[java]
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参数表
[java]
/**
* 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);
补充:移动开发 , Android ,