导航:首页 > IDC知识 > android向服务器发送数据

android向服务器发送数据

发布时间:2020-12-22 18:51:32

1、android向服务器发送数据问题

HttpURLConnection.openConnection();

就可以了 HttpURLConnection 可以实现 发送接收文字 文件流 等,

具体就是 例如 :
URL url =new URL("xxxxxxxxxxxxxxx") (url不用解释吧)

(HttpURLConnection).openConnection();

就可以将一些版 URL 里包含的信息字符发过去了权 ;

JSP页面会收到 request请求 之后就简单了吧

2、Android 以Get方法向服务器提交数据,参数里含有中文

可以用抄Get方式实现;

方法:通过拼接url在url后添加相应的数据,如:http://IPvideonews/GetInfoServlet?title=霍比特人&timelength=100;

缺点:通过Get方式提交数据只能发送2K以内的数据,适合发送容量较小的数据,另外,如果发送的数据是中文,则需要对url和服务器端做相应的乱码处理(设置能显示中文的编码方式),否则会产生乱码问题。

处理方式如下:

3、web端的项目怎么向Android端服务器发送请求?

可使用Android自带的httpClient实现Android与java web之间的数据的交互。
具体实现代码:
1. GET 方式传递参数
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "数据")); //增加参数1
params.add(new BasicNameValuePair("param2", "value2"));//增加参数2
String param = URLEncodedUtils.format(params, "UTF-8");//对参数编码
String baseUrl = "服务器接口完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//将URL与参数拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
2. POST方式 方式传递参数
//和GET方式一样,先将参数放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加参数1
params.add(new BasicNameValuePair("param2", "第二个参数"));//增加参数2
try {
HttpPost postMethod = new HttpPost(baseUrl);//创建一个post请求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //执行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

4、android开发客户端,已知服务器的IP和端口,如何给该服务器发送数据?

用socket套接字,与服务器段建立连接,通过获得socket的输入输出流来进行数据传输与接受,发数据就用outputstream的write方法

5、怎么实现服务器给android客户端主动推送消息

采用MQTT协议实现Android推送功能是一种解决方案。MQTT是一个轻量级的消息发布/订阅协议,是实现基于手机客户端的消息推送服务器的理想解决方案。 

常见的解决方案实现原理:

1、轮询(Pull)方式:客户端定时向服务器发送询问消息,一旦服务器有变化则立即同步消息。

2、SMS(Push)方式:通过拦截SMS消息并且解析消息内容来了解服务器的命令,但这种方式一般用户在经济上很难承受。

3、持久连接(Push)方式:客户端和服务器之间建立长久连接,这样就可以实现消息的及时行和实时性。

(5)android向服务器发送数据扩展资料:

推送消息注意事项:

1、支持第三方推送内容,是要客户端和服务器都支持的,客户端和服务器都导入推送SDK。

2、服务器推送内容,可以精确指定推送时间,推送的具体接收人,用户群,位置。

3、即推送的维度可以使时间,位置,人群。

4、极光使用了两种不同的通知方式,一种是推送通知,一种是推送消息。

5、如果要使用androidpn,则还需要做大量的工作,需要理解XMPP协议、理解Androidpn的实现机制,需要调试内部存在的BUG。

参考资料来源:网络-服务器

参考资料来源:网络-Android客户端

参考资料来源:网络-信息推送

6、android做客户端socket如何让点击按钮向服务器发送信息

使用基于TCP协议的Socket
一个客户端要发起一次通信,首先必须知道运行服务器端的主机IP地址。然后由网络基础设施利用目标地址,将客户端发送的信息传递到正确的主机上,在Java中,地址可以由一个字符串来定义,这个字符串可以使数字型的地址(比如192.168.1.1),也可以是主机名(example.com)。
而在android 4.0 之后系统以后就禁止在主线程中进行网络访问了,原因是:

主线程是负责UI的响应,如果在主线程进行网络访问,超过5秒的话就会引发强制关闭,所以这种耗时的操作不能放在主线程里。放在子线程里,而子线程里是不能对主线程的UI进行改变的,因此就引出了Handler,主线程里定义Handler,子线程里使用。
以下是一个android socket客户端的例子:
---------------------------------Java代码---------------------------------------
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class TCPSocketActivity extends Activity {

public static final String TAG = TCPSocketActivity.class.getSimpleName();

/* 服务器地址 */
private String host_ip = null;
/* 服务器端口 */
private int host_port = 0;

private Button btnConnect;
private Button btnSend;
private EditText editSend;
private EditText hostIP;
private EditText hostPort;
private Socket socket;
private PrintStream output;
private String buffer = "";
private Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_test);
context = this;
initView();

btnConnect.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
host_ip = hostIP.getText().toString();
host_port = Integer.parseInt(hostPort.getText().toString());
new Thread(new ConnectThread()).start();
}
});

btnSend.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new SendThread(editSend.getText().toString())).start();
}
});
}

private void toastText(String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}

public void handleException(Exception e, String prefix) {
e.printStackTrace();
toastText(prefix + e.toString());
}

public void initView() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnSend = (Button) findViewById(R.id.btnSend);
editSend = (EditText) findViewById(R.id.sendMsg);
hostIP = (EditText) findViewById(R.id.hostIP);
hostPort = (EditText) findViewById(R.id.hostPort);
}

private void closeSocket() {
try {
output.close();
socket.close();
} catch (IOException e) {
handleException(e, "close exception: ");
}
}

Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (0x123 == msg.what) {
toastText("连接成功!");
}
}
};

/* 连接socket线程 */
public class ConnectThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
if (null == socket || socket.isClosed()) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
output = new PrintStream(socket.getOutputStream(), true,
"utf-8");
}
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/*发送信息线程*/
public class SendThread implements Runnable {

String msg;

public SendThread(String msg) {
super();
this.msg = msg;
}

@Override
public void run() {
// TODO Auto-generated method stub
try {
output.print(msg);
} catch (Exception e) {
e.printStackTrace();
}
closeSocket();
}

}

public class SocketThread implements Runnable {
public String txt1;

public SocketThread(String txt1) {
super();
this.txt1 = txt1;
}

@Override
public void run() {
// TODO Auto-generated method stub
Message msg = Message.obtain();
try {
/* 连接服务器 并设置连接超时为5秒 */
if (socket.isClosed() || null == socket) {
socket = new Socket();
socket.connect(new InetSocketAddress(host_ip,host_port),5000);
}
// 获取输入输出流
PrintStream ou = new PrintStream(socket.getOutputStream(),
true, "UTF-8");
BufferedReader bff = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 读取发来服务器信息
String line = null;
buffer = "";
while ((line = bff.readLine()) != null) {
buffer = line + buffer;
}

// 向服务器发送信息
ou.print(txt1);
ou.flush();
// 关闭各种输入输出流
bff.close();
ou.close();
socket.close();
msg.what = 0x123;
handler.sendMessage(msg);
} catch (UnknownHostException e) {
} catch (IOException e) {
}
}
}
}
-----------------------------布局文件activity_socket_test.xml--------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="vertical" >

<EditText
android:id="@+id/hostIP"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="服务器ip"
android:singleLine="true"
android:inputType="text" />

<EditText
android:id="@+id/hostPort"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="端口"
android:singleLine="true"
android:inputType="number" />

<Button
android:id="@+id/btnConnect"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:background="@drawable/style_btn_shape"
android:layout_margin="5dip"
android:text="@string/connect"
android:textColor="@color/white" />

<EditText
android:id="@+id/sendMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:hint="需要发送的内容"
android:inputType="text" />

<Button
android:id="@+id/btnSend"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:background="@drawable/style_btn_shape"
android:layout_gravity="center_vertical|center_horizontal"
android:text="@string/send"
android:textColor="@color/white" />

</LinearLayout>
-------------------------样式文件style_btn_shape.xml----------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充的颜色 -->
<solid android:color="#0465b2" />
<!-- 设置按钮的四个角为弧形 -->
<!-- android:radius 弧形的半径 -->
<corners android:radius="15dip" />

<!-- padding:Button里面的文字与Button边界的间隔 -->
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp"
/>
</shape>
------------------------------END---------------------------------------

7、Android向服务器post数据的问题

private void toUploadFile(File file, String fileKey, String RequestURL,
Map<String, String> param) {
imgUrl = null;
String result = null;
requestTime = 0;
conn = null;
long requestTime = System.currentTimeMillis();
long responseTime = 0;

try {
URL url = new URL(RequestURL);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码

if (APPConfiguration.USER_LOADING == 1) {
conn.setRequestProperty("platform", APP_TOSERVER.Platform);
} else if (APPConfiguration.USER_LOADING == 2) {
conn.setRequestProperty("userId", APP_TOSERVER.UserId);
conn.setRequestProperty("userToken", APP_TOSERVER.UserToken);
conn.setRequestProperty("machineImei", APP_TOSERVER.MachineImei);
conn.setRequestProperty("version", APP_TOSERVER.Version);
conn.setRequestProperty("platform", APP_TOSERVER.Platform);
}

conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
// conn.setRequestProperty("enctype", "multipart/form-data");

/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = "";

/***
* 以下是用于上传参数
*/
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"")
.append(key).append("\"").append(LINE_END)
.append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
Log.i(TAG, key + "=" + params + "##");
dos.write(params.getBytes());
dos.flush();
}
}

sb = null;
params = null;
sb = new StringBuffer();
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + fileKey
+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的
// ,用于服务器端辨别文件的类型的
sb.append(LINE_END);
params = sb.toString();
sb = null;

Log.i(TAG, file.getName() + "=" + params + "##");
dos.write(params.getBytes());
/** 上传文件 */
InputStream is = new FileInputStream(file);
onUploadProcessListener.initUpload((int) file.length());
byte[] bytes = new byte[1024];
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
dos.write(bytes, 0, len);
Log.i(TAG, "curLen:" + curLen);
onUploadProcessListener.onUploadProcess(curLen);
}
is.close();

dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
//
// dos.write(tempOutputStream.toByteArray());
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
responseTime = System.currentTimeMillis();
this.requestTime = (int) ((responseTime - requestTime) / 1000);
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
BufferedReader input = new BufferedReader(
new InputStreamReader(conn.getInputStream(), CHARSET));
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + handleString(result));
readJSON(handleString(result));
sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:" + handleString(result));
return;
} else {
Log.e(TAG, "request error");
sendMessage(UPLOAD_SERVER_ERROR_CODE, "上传失败:code=" + res);
return;
}
} catch (MalformedURLException e) {
disconnection();
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());
Log.e(TAG, "上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
} catch (IOException e) {
disconnection();
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());

Log.e(TAG, "上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
} catch (Exception e) {
e.printStackTrace();
disconnection();
sendMessage(UPLOAD_SERVER_ERROR_CODE,
"上传失败:error=" + e.getMessage());

Log.e(TAG, "上传失败:error=" + e.getMessage());
}
}

8、新手求助,Android实现向服务器发送数据的问题

可使用android自带的httpclient框架实现。

1. GET 方式传递参数
//先将参数放入List,再对参数进行URL编码
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "数据")); //增加参数1
params.add(new BasicNameValuePair("param2", "value2"));//增加参数2
String param = URLEncodedUtils.format(params, "UTF-8");//对参数编码
String baseUrl = "服务器接口完整URL";
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);//将URL与参数拼接
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//获取服务器响应内容
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

2. POST方式 方式传递参数
//和GET方式一样,先将参数放入List
params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("param1", "Post方法"));//增加参数1
params.add(new BasicNameValuePair("param2", "第二个参数"));//增加参数2
try {
HttpPost postMethod = new HttpPost(baseUrl);//创建一个post请求
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //执行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //获取响应码
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //获取响应内容
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

9、android怎么实现Tomcat服务器向指定手机发送数据?

这个应该就是推送的功能,我们用的极光的推送有离线推送的这个功能,要是自己写的话功能比较复杂,就需要用socret 长连接等

与android向服务器发送数据相关的知识