如何在Android下编码互联网连接?
我正在用Android编写不同的应用程序,他们中的大多数人使用互联网与服务器通信。我想知道如何编写这个项目,让Android与服务器通信。我已经编写了需要检查的代码: 1) 该设备已连接到Internet 2) 目标的url已更正并写入 3) 服务器启动了 所以我不是问如何检查这些东西,而是问如何在代码中放置这些方法。 例如,我的应用程序需要向服务器发送带有字符串(例如名称)的http请求。所以我编写了一个AsynTask,它需要两个字符串作为输入(IP和参数),仅此而已。在发送AsynTask之前或在该类中,我是否应该检查一切是否正常?如何在Android下编码互联网连接?,android,connection,Android,Connection,我正在用Android编写不同的应用程序,他们中的大多数人使用互联网与服务器通信。我想知道如何编写这个项目,让Android与服务器通信。我已经编写了需要检查的代码: 1) 该设备已连接到Internet 2) 目标的url已更正并写入 3) 服务器启动了 所以我不是问如何检查这些东西,而是问如何在代码中放置这些方法。 例如,我的应用程序需要向服务器发送带有字符串(例如名称)的http请求。所以我编写了一个AsynTask,它需要两个字符串作为输入(IP和参数),仅此而已。在发送AsynTask
提前感谢您的回复。首先,您不能在主线程上运行网络,这一点需要您知道。现在,我将为您发布两个代码。第一个是将某个文件上载到服务器,第二个是如何在android上与mysql服务器通信。第二个是我提供了一个链接,介绍如何在android上完全使用源代码下载。让我们开始吧。第一个将文件上传到服务器的代码
package com.androidexample.uploadtoserver;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UploadToServer extends Activity {
TextView messageText;
Button uploadButton;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
final String uploadFilePath = "/mnt/sdcard/";
final String uploadFileName = "test.jpg";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_to_server);
uploadButton = (Button)findViewById(R.id.uploadButton);
messageText = (TextView)findViewById(R.id.messageText);
messageText.setText("Uploading file path :- '/mnt/sdcard/"+uploadFileName+"'");
/************* Php script path ****************/
upLoadServerUri = "http://54.148.41.171/UploadToServer.php";
uploadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
uploadFile(uploadFilePath + "" + uploadFileName);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String fileName= sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
这是服务器端代码
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
这段代码的魅力在于你可以粘贴到MainActivity中,这意味着你可以在主线程上运行这段代码,而无需在后台运行,不是吗?:)现在让我们来看第二段代码,在这里你可以与mysql服务器进行很好的通信!几乎没有忘记您必须在服务器端创建上载文件夹:)
这是教程,非常棒,相信我!
享受:)对于程序设计问题,我建议您访问。似乎您只需要确定一组原则/模式。单一责任原则是一个良好的开端。谢谢您的回复。嗯,你可能会回答我一直在寻找的一个可能的解决方案。从编码的角度来看,这个类似乎太长了,但它可以工作。您认为可以在异步任务中创建try-and-catch吗?如果连接良好,您认为最好检查活动?在这种情况下,SR原则是不受尊重的。好吧,首先你不需要使用异步任务,因为你不能使用try-and-catch,所以你很难知道如果java不能执行asynvtask会发生什么,相信我,我已经为此奋斗了4个月了!那么活动检查连接呢?它是最棒的一个,因为它可以全面检查任何互联网的可能性,它就像一个线程,很小但功能强大,所以我很高兴听到我能帮助你相信我,我很高兴:)))哦,那长时间呢没有什么好的代码是短的记住