導航:首頁 > 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向伺服器發送數據相關的知識