Android怎么连接Web服务器 ?

PerfectSuperman 2011-08-22 01:43:05
给一个php网站做一个手机客户端应用软件.

但是不知道怎么连接服务器端

我知道用httpConnection什么的...

但是我想知道:如果想调用服务器端的getInfo(int id)方法,客户端怎么实现,最好给出代码

请懂的哥们给指导下啊,谢谢!
...全文
5052 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
降龙 2011-10-08
  • 打赏
  • 举报
回复
使用webservice,利用KSOAP,一般返回的数据是xml格式或者json格式的,对其解析获取自己想要的信息即可~~~~
小裴同学 2011-10-08
  • 打赏
  • 举报
回复
方法很多,发个工具类你参考下
package com.jftt.market.network;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.List;

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.jftt.market.common.CONST;

/**
* class name:HttpConnect<BR>
* class description:get something to web <BR>
* PS: <BR>
*
* @version 1.00 2011/09/21
* @author CODYY)peijiangping
*/
public class HttpConnect {

private String url;
private HttpPost httpRequest;
private HttpResponse httpResponse;
private HttpParams httpParams;
private HttpClient httpClient;

public HttpConnect(String url) {
this.url = url;
httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
CONST.HTTP_CONNECT_TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParams,
CONST.HTTP_SOCKET_TIME_OUT);
httpClient = new DefaultHttpClient(httpParams);
}

public InputStream getDataAsInputStream(List<NameValuePair> params) {
InputStream result = null;
try {
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = httpClient.execute(httpRequest);

if (CONST.HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
result = httpResponse.getEntity().getContent();
}

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
}
return result;
}

public String getDataAsString(List<NameValuePair> params) {
String result = null;
try {
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = httpClient.execute(httpRequest);

if (CONST.HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
}
return result;
}

public int getDataAsInt(List<NameValuePair> params) {
int result = CONST.HTTP_ERROR;
try {
httpRequest = new HttpPost(url);
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = httpClient.execute(httpRequest);

if (CONST.HTTP_OK == httpResponse.getStatusLine().getStatusCode()) {
result = Integer.parseInt(EntityUtils.toString(httpResponse
.getEntity()));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(CONST.LOG_TAG, e.getMessage(), e);
return result;
}
return result;
}

}

lww200888 2011-10-08
  • 打赏
  • 举报
回复
使用webservice 别忘了设置一些必要的属性。
Calon Mo 2011-10-07
  • 打赏
  • 举报
回复
我们也有个项目是android访问服务器端的,我们的数据传输格式为json,android端可以用谷歌提供的gson进行解析,服务器端是用tomcat,采用spring mvc架构,android端是直接访问标在方法头端的那个地址的,你懂spring mvc的话就知道的,也就是相当于方法调用而已。
plike001 2011-10-07
  • 打赏
  • 举报
回复
mark 学习了
cijiu 2011-09-30
  • 打赏
  • 举报
回复
很好 对我很有用
超级码妖 2011-09-01
  • 打赏
  • 举报
回复
我是用json传数据的

public void actAddItemClick() throws ApiException, ParseException {
Cursor cur = null;

String HTTP_HOST = "http://www.pvtool.com";
String loc_id, parent_id;
String loc_name;
float yearsunrate;
int sunratetime;
int maxsunratetime;

maxsunratetime = 0;
try {
cur = this.db.rawQuery("SELECT theValue FROM sys_conf WHERE theVar=?", new String[]{ "sunratetime" });

cur.moveToFirst();
if (!cur.isAfterLast())
maxsunratetime = cur.getInt(0);
} catch (Exception e) {
e.printStackTrace();
}finally {
cur.close();
}

String content = getUrlContent(String.format(HTTP_HOST+"/forum/sunratexml.php?ud=%d", maxsunratetime));

try {
JSONArray locs = new JSONArray(content);
for (int i=0;i < locs.length(); i++) {
JSONObject loc = locs.getJSONObject(i);
loc_id = loc.getString("location_id");
parent_id = loc.getString("parent_id");
loc_name = loc.getString("location_name");
yearsunrate = loc.getLong("yearsunrate");
sunratetime = loc.getInt("sunratetime");

if (sunratetime>maxsunratetime)
maxsunratetime = sunratetime;

try {
cur = db.rawQuery("SELECT location_id FROM sunrate WHERE location_id=?",
new String[] { loc_id });

cur.moveToFirst();
if (!cur.isAfterLast())
db.execSQL("UPDATE sunrate SET avgtime=? WHERE location_id=?",
new Object[] { yearsunrate, loc_id });
else
db.execSQL("INSERT INTO sunrate(avgtime,city,location_id,parent_id) VALUES(?,?,?,?)",
new Object[] { yearsunrate, loc_name, loc_id, parent_id });
} finally {
cur.close();
}

db.execSQL("UPDATE sunrate SET theValue=? WHERE theVar=?",
new Object[] { yearsunrate, loc_id });
}

db.execSQL("UPDATE sys_conf SET theValue=? WHERE theVar=?",
new Object[] { maxsunratetime, "sunratetime" });

//java和php一样,TimeStamp都是以1970-01-01 00:00:00.000开始计算
Toast.makeText(context, new SimpleDateFormat("最新数据时间:yyyy年MM月dd日 HH:mm").format(new Timestamp(maxsunratetime)), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
throw new ParseException("Problem parsing API response", e);
}
}

protected static synchronized String getUrlContent(String url)
throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}

Log.i(TAG, "URL:"+url);

//HttpParams httpParameters = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
//HttpConnectionParams.setSoTimeout(httpParameters, 5000);
//HttpClient client = new DefaultHttpClient(httpParameters);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("User-Agent", sUserAgent); // 设置客户端标识

try {
HttpResponse response = client.execute(request);

StatusLine status = response.getStatusLine();
if (status.getStatusCode() != 200) {
throw new ApiException("Invalid response from server: "
+ status.toString());
}

HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent(); // 获取HTTP返回的数据流

ByteArrayOutputStream content = new ByteArrayOutputStream();

int readBytes = 0;
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes); // 转化为字节数组流
}

return new String(content.toByteArray()); // 从字节数组构建String
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}
}

protected static synchronized String putUrlContent(String url, Map<String, String> params, Map<String, File> files)
throws ApiException {
if (sUserAgent == null) {
throw new ApiException("User-Agent string must be prepared");
}

Log.i(TAG, "PUTURL:"+url);

String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
String data = "";

try {
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false);
conn.setRequestMethod("POST"); //Post方式
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("User-Agent", sUserAgent); // 设置客户端标识
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);

// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}

DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());

// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"fileupload\"; filename=\""
+ file.getKey() + "\"" + LINEND);
sb1.append("Content-Type: image/jpeg" + LINEND);
//sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());

InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}

is.close();
outStream.write(LINEND.getBytes());
}

// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();

// 得到响应码
int res = conn.getResponseCode();
String line = null;
InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
while((line = bufReader.readLine())!=null)
data += line;

if (res != 200) {
throw new ApiException("Invalid response from server: "
+ data);
}

in.close();
outStream.close();
conn.disconnect();
} catch (IOException e) {
throw new ApiException("Problem communicating with API", e);
}

return data;
}
laukie 2011-08-26
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 liuyuan0404 的回复:]

使用webservice
[/Quote]

+1,这个是正解
pmlxp 2011-08-26
  • 打赏
  • 举报
回复
不错
学习了
78 2011-08-26
  • 打赏
  • 举报
回复
就知道吹些空的。

楼主,给你一段代码(直接调Webservice,当然webservice上有对应的web方法):


final static String SOAP_ACTION = "http://www.XXX.com";
private static final String NAMESPACE = "http://www.XXX.com/";
private static final String URL = "http://192.168.61.160/webserver/OperatingCenterService.asmx";
public static boolean isFirstLogin(String loginid)
{
/*是不是第一次登录,是返回真*/
String url = URL + "/FirstLogin";
HttpPost request = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("loginid", loginid));
try {

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
HTTP.UTF_8);

request.setEntity(entity);
HttpResponse response = new DefaultHttpClient().execute(request);

if (response.getStatusLine().getStatusCode() == 200) {

// ParserMachine.parse_onefirstLogin是对response.getEntity()的解析过程。
return ParserMachine.parse_onefirstLogin(EntityUtils.toString(response
.getEntity()));



} else {
return false;
}

} catch (Exception e) {

return false;
}

}
luzhiqin 2011-08-26
  • 打赏
  • 举报
回复
webservice
PerfectSuperman 2011-08-23
  • 打赏
  • 举报
回复
内部类中包含管理你用IDL生成的远程过程调用需要的所有代码。两个内部类都实现了IBinder 接口。其中一个在本地由系统内部使用,写代码时可以忽略它。另一个叫做 Stub,扩展自Binder 类。作为对执行IPC调用的内部代码补充,它包含你在RPC接口中声明的方法。象图中说明的那样, 你应该继承Stub来实现这些方法。

一般远程过程由服务来管理(因为服务可以通知系统关于进程和它连接的其它进程的信息)。它既有aidl。服务的客户端只有由aidl生成的接口文件。

接下来是服务和其客户端是如何建立连接的:

服务的客户端(为位于本地)应该实现onServiceConnected() 和onServiceDisconnected() 方法,这样它们就可以在成功与远程服务建立或断开连接后收到消息。它们应该调用bindService() 来设置连接。
服务的onBind() 方法应该被实现用作根据收到的意图(传入bindService()的意图),决定接受或拒绝连接。
如果连接被接受,它返回一个Stub的子类。如果服务接受了连接,Android调用客户端的onServiceConnected() 方法并传入一个IBinder对象,由服务管理的Stub子类的代理。通过该代理,客户端可以调用远程服务。
上述简单的描述忽略了一些RPC机制的细节。更多信息参见用AIDL设计远程接口和IBinder 类的描述。



在Android中, 每个应用程序都可以有自己的进程. 在写UI应用的时候, 经常要用到Service. 在不同的进程中, 怎样传递对象呢? 显然, Java中不允许跨进程内存共享. 因此传递对象, 只能把对象拆分成操作系统能理解的简单形式, 以达到跨界对象访问的目的. 在J2EE中,采用RMI的方式, 可以通过序列化传递对象. 在Android中, 则采用AIDL的方式. 理论上AIDL可以传递Bundle,实际上做起来却比较麻烦.

AIDL(AndRoid接口描述语言)是一种借口描述语言; 编译器可以通过aidl文件生成一段代码,通过预先定义的接口达到两个进程内部通信进程的目的. 如果需要在一个Activity中, 访问另一个Service中的某个对象, 需要先将对象转化成AIDL可识别的参数(可能是多个参数), 然后使用AIDL来传递这些参数, 在消息的接收端, 使用这些参数组装成自己需要的对象.

AIDL的IPC的机制和COM或CORBA类似, 是基于接口的,但它是轻量级的。它使用代理类在客户端和实现层间传递值. 如果要使用AIDL, 需要完成2件事情: 1. 引入AIDL的相关类.; 2. 调用aidl产生的class.
lyjiang126 2011-08-22
  • 打赏
  • 举报
回复
调用方法的话好像是用webservice,连接服务器一般都是访问某个地址,然后返回特定格式的数据,如xml、json,客户端获取数据然后解析,这样应该要简单点。
PerfectSuperman 2011-08-22
  • 打赏
  • 举报
回复
如果想调用服务器端的getInfo(int id)方法,客户端怎么实现,请给出代码!
[Quote=引用 1 楼 liuyuan0404 的回复:]

使用webservice
[/Quote]
liuyuan0404 2011-08-22
  • 打赏
  • 举报
回复
使用webservice

80,349

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧