社区
其他技术讨论专区
帖子详情
Android,从应用程序发送字符串到网络服务器
weixin_38078374
2019-09-12 03:12:09
我想做一个应用程序,我应该从应用程序发送数据到Web服务器。 到目前为止,我一直在搜索,但无法找到一个工作的例子,我发现一些使用asynctask哪些不起作用,所以任何帮助表示赞赏!
...全文
32
2
打赏
收藏
Android,从应用程序发送字符串到网络服务器
我想做一个应用程序,我应该从应用程序发送数据到Web服务器。 到目前为止,我一直在搜索,但无法找到一个工作的例子,我发现一些使用asynctask哪些不起作用,所以任何帮助表示赞赏!
复制链接
扫一扫
分享
转发到动态
举报
AI
作业
写回复
配置赞助广告
用AI写文章
2 条
回复
切换为时间正序
请发表友善的回复…
发表回复
打赏红包
weixin_38083061
2019-09-12
打赏
举报
回复
试试下面的代码: - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONObject; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import android.app.Activity; import com.hmkcode.android.vo.Person; public class MainActivity extends Activity implements OnClickListener { TextView tvIsConnected; EditText etName,etCountry,etTwitter; Button btnPost; Person person; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get reference to the views tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); etName = (EditText) findViewById(R.id.etName); etCountry = (EditText) findViewById(R.id.etCountry); etTwitter = (EditText) findViewById(R.id.etTwitter); btnPost = (Button) findViewById(R.id.btnPost); // check if you are connected or not if(isConnected()){ tvIsConnected.setBackgroundColor(0xFF00CC00); tvIsConnected.setText("You are conncted"); } else{ tvIsConnected.setText("You are NOT conncted"); } // add click listener to Button "POST" btnPost.setOnClickListener(this); } public static String POST(String url, Person person){ InputStream inputStream = null; String result = ""; try { // 1. create HttpClient HttpClient httpclient = new DefaultHttpClient(); // 2. make POST request to the given URL HttpPost httpPost = new HttpPost(url); String json = ""; // 3. build jsonObject JSONObject jsonObject = new JSONObject(); jsonObject.accumulate("name", person.getName()); jsonObject.accumulate("country", person.getCountry()); jsonObject.accumulate("twitter", person.getTwitter()); // 4. convert JSONObject to JSON to String json = jsonObject.toString(); // ** Alternative way to convert Person object to JSON string usin Jackson Lib // ObjectMapper mapper = new ObjectMapper(); // json = mapper.writeValueAsString(person); // 5. set json to StringEntity StringEntity se = new StringEntity(json); // 6. set httpPost Entity httpPost.setEntity(se); // 7. Set some headers to inform server about the type of the content httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); // 8. Execute POST request to the given URL HttpResponse httpResponse = httpclient.execute(httpPost); // 9. receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // 10. convert inputstream to string if(inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!"; } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } // 11. return result return result; } public boolean isConnected(){ ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } @Override public void onClick(View view) { switch(view.getId()){ case R.id.btnPost: if(!validate()) Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show(); // call AsynTask to perform network operation on separate thread new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet"); break; } } private class HttpAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { person = new Person(); person.setName(etName.getText().toString()); person.setCountry(etCountry.getText().toString()); person.setTwitter(etTwitter.getText().toString()); return POST(urls[0],person); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show(); } } private boolean validate(){ if(etName.getText().toString().trim().equals("")) return false; else if(etCountry.getText().toString().trim().equals("")) return false; else if(etTwitter.getText().toString().trim().equals("")) return false; else return true; } private static String convertInputStreamToString(InputStream inputStream) throws IOException{ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } } 见下面的链接了解更多信息: - http://hmkcode.com/android-send-json-data-to-server/ http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89
weixin_38087646
2019-09-12
打赏
举报
回复
试试这个, import java.util.ArrayList; 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.ResponseHandler; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.AsyncTask; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; public class AdminLogin extends Activity { EditText adminUN, adminPass; CheckBox cb; Button loginBtn; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; List<NameValuePair> nameValuePairs; // Your IP address or your website complete address String adminLoginURL = "http://192.168.1.1/admin_login.php"; ProgressDialog dialog = null; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.admin_login); loginBtn = (Button) findViewById(R.id.adminLogin); adminUN = (EditText) findViewById(R.id.adminUName); adminPass = (EditText) findViewById(R.id.adminPass); loginBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Admin_Login().execute(); } }); } class Admin_Login extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); dialog = new ProgressDialog(AdminLogin.this); dialog.setMessage("Please Wait..!"); dialog.setIndeterminate(false); dialog.setCancelable(true); dialog.show(); } protected String doInBackground(String... params) { new Thread(new Runnable() { public void run() { login(); } }).start(); return null; } protected void onPostExecute(String file_url) { // dismiss the dialog once got all details dialog.dismiss(); } } void login() { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost(adminLoginURL); // add your data nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username", adminUN .getText().toString().trim())); nameValuePairs.add(new BasicNameValuePair("password", adminPass .getText().toString().trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request response = httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); boolean matches = response.startsWith("User Found"); if (matches) { // Do something start an Activity or do anything you wanted } } else { showAlert(); } } catch (Exception e) { dialog.dismiss(); System.out.println("Exception : " + e.getMessage()); } } public void showAlert() { AdminLogin.this.runOnUiThread(new Runnable() { public void run() { AlertDialog.Builder builder = new AlertDialog.Builder( AdminLogin.this); builder.setTitle("Login Error."); builder.setMessage("User not Found.") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert = builder.create(); alert.show(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu items for use in the action bar MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_exit, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle presses on the action bar items switch (item.getItemId()) { case R.id.action_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } } 创建一个.xml文件来获取用户名,密码和登录按钮 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/ic_wall" android:gravity="center_horizontal" android:orientation="vertical" > <EditText android:id="@+id/adminUName" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginTop="50dip" android:hint="Username" android:singleLine="true" /> <requestFocus /> <EditText android:id="@+id/adminPass" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:ems="10" android:hint="Password" android:inputType="textPassword" android:singleLine="true" /> <Button android:id="@+id/adminLogin" android:layout_width="150dp" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="20dip" android:text="Login" android:textColor="#0b84aa" /> </LinearLayout> 你必须有phpMyAdmin尝试这种在本地系统中,如果你有托管服务器,然后尝试部分使用下面的PHP代码并运行它。 adminLogin.php <?php $hostname_localhost =""; $database_localhost =""; $username_localhost =""; $password_localhost =""; # Make sure above fields are filled with your config values (must) $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR); mysql_select_db($database_localhost, $localhost); if (empty($_POST['username'])) { echo "Please Enter a name"; } else { $username = $_POST['username']; } if (empty($_POST['password'])) { echo "Please Enter Your Password "; } else { $password = SHA1($_POST['password']); } $query_search = "select * from adminregister where username = '".$username."' AND password = '".$password."'"; $query_exec = mysql_query($query_search) or die(mysql_error()); $rows = mysql_num_rows($query_exec); //echo $rows; if($rows == 0) { echo "\nNo Such User Found"; } else { echo "User Found"; } mysql_close(); ?> 注意:您需要在MySQL中创建指定的数据库和表饲料和检索数据 如果有任何错误,请发表评论。
Android
通过webservice连接Sqlserver实例
Android
连接SQLServer详细教程(数据库+
服务器
+客户端) 博客http://blog.csdn.net/zhyl8157121/article/details/8169172中的资源
Android
的socket长连接(心跳检测)
这是
Android
的socket长连接(心跳包),由于本人项目中需要用到长连接,所以先做了个demo,亲测是没有问题的。
Android
Http URL Connection获取数据并JSON解析
本文主要讲解,通过HttpURLConnection从服务端获取数据,然后经过JSON解析后,显示在手机屏幕上。
Android
(客户端)与Linux(
服务器
端)进行TCP数据通信
最近,做项目需要使用
Android
(客户端)与Linux(
服务器
端)进行数据通信,这学期也刚好学习了Linux
网络
编程的一些知识。所以,实现了一个小Demo,供有需要的朋友参考一下。效果如下:客户端向
服务器
端
发送
字符串
数据,
服务器
收到客户端的数据显示在Linux终端上,并往客户端回发接收到的数据。客户端把发往
服务器
端的数据与接收到的数据都显示在一个TextView上面。Linux
服务器
端:Andro
巧用
Android
网络
通信技术,在
网络
上直接传输对象
要做一个优秀的
Android
应用,使用到
网络
通信技术是必不可少的,很难想象一款没有
网络
交互的软件最终能发展得多成功。那么我们来看一下,一般
Android
应用程序
里都是怎么实现
网络
交互的,这里拿一个Boook对象为例,首先在手机端生成一个Book对象,里面包含书名、作者、价格等数据。为了要将这些数据
发送
到
服务器
端,我们要从Book对象中把数据取出,然后组装成XML格式的
字符串
。接着通过
网络
API,把组装好的XML
字符串
发送
到
服务器
端。
服务器
端接到了客户端发来的XML
字符串
,就要对该XML进行解析。然后把解析出
其他技术讨论专区
473
社区成员
791,201
社区内容
发帖
与我相关
我的任务
其他技术讨论专区
其他技术讨论专区
复制链接
扫一扫
分享
社区描述
其他技术讨论专区
其他
技术论坛(原bbs)
社区管理员
加入社区
获取链接或二维码
近7日
近30日
至今
加载中
查看更多榜单
社区公告
暂无公告
试试用AI创作助手写篇文章吧
+ 用AI写文章