Android,从应用程序发送字符串到网络服务器

我想做一个应用程序,我应该从应用程序发送数据到Web服务器。 到目前为止,我一直在搜索,但无法找到一个工作的例子,我发现一些使用asynctask哪些不起作用,所以任何帮助表示赞赏!Android,从应用程序发送字符串到网络服务器

回答:

试试下面的代码: -

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

回答:

试试这个,

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,从应用程序发送字符串到网络服务器 的全部内容, 来源链接: utcz.com/qa/261869.html

回到顶部