使用post方法将android应用程序连接到webserver

时间:2016-02-13 13:29:26

标签: java php android mysql

我试图创建一个简单的Android应用程序,其中我试图将我的应用程序连接到我有一个名为akshaynsit1_pathaniswaad的数据库的网络服务器,在该数据库中我有一个名为table1的表。在这个表中,我有3列id(int自动增量主键),name(varchar(30)),addr varchar(30)。我正在创建一个简单的注册页面,用户将在其中添加他的名字和地址,这个名称和地址将通过post方法保存到我的网络服务器。 我的MainActivity.java如下

包com.example.akshay007.sample;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    EditText ed1,ed2;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed1=(EditText)findViewById(R.id.editText);
        ed2=(EditText)findViewById(R.id.editText2);
        tv=(TextView)findViewById(R.id.textView2);
    }

    public void insert(View view){
        String name = ed1.getText().toString();
        String add = ed2.getText().toString();

        insertToDatabase(name,add);
    }

    private void insertToDatabase(String name, String add){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                String paramUsername = params[0];
                String paramAddress = params[1];
                try{
                    String name = paramUsername;
                    String address = paramAddress;

                    String link="http://http://pathaniswaad.com/android_akshay/post.php";
                    String data  = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
                    data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8");

                    URL url = new URL(link);
                    URLConnection conn = url.openConnection();

                    conn.setDoOutput(true);
                    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

                    wr.write( data );
                    wr.flush();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

                    StringBuilder sb = new StringBuilder();
                    String line = null;

                    // Read Server Response
                    while((line = reader.readLine()) != null)
                    {
                        sb.append(line);
                        break;
                    }
                    return sb.toString();
                }
                catch(Exception e){
                    return new String("Exception: " + e.getMessage());
                }
                //return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(getApplicationContext(), "yo bro", Toast.LENGTH_LONG).show();
                //TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
                //textViewResult.setText("Inserted");
                //tv.setText("ya brah..");
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(name, add);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

activity_main.xml如下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_alignParentTop="true"
        android:hint="name"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="121dp" />

    <EditText
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:hint="address"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Signup"
        android:id="@+id/button"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="56dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Merchant Signup"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="44dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/textView2"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Androidmanifest.xml如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.akshay007.sample" >

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我的post.php脚本如下

<?php
$con = mysqli_connect("65.50.265.181:336","jfjtyfyfhjfjdy","uitytityut67","akshaynsit1_pathaniswaad");

if (mysqli_connect_errno($con))
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
    echo"connection successful <br>";
}
$name = $_POST['name'];
$address = $_POST['address'];
$result = mysqli_query($con,"insert into table1 (name,addr) values ('$name','$address')");
if(mysqli_query($con,$sql)){
    echo 'success';
  }
  else{
    echo 'failure';
  }
  mysqli_close($con);
?>

请帮助任何形式的帮助将不胜感激!!!!!!!!!!

2 个答案:

答案 0 :(得分:0)

如果您的清单文件中尚未包含此内容,请在<application>部分之前添加:

<uses-permission android:name="android.permission.INTERNET" />

另外,我注意到代码中的链接是

http://http://pathaniswaad.com/android_akshay/post.php

尝试将其更改为

http://pathaniswaad.com/android_akshay/post.php

正如其他用户也指出的那样,你需要附加参数。使用loopj HttpAsyncClient有一种更好的方法:

添加到您的gradle版本:

compile 'com.loopj.android:android-async-http:1.4.9'

这是我为GitHub Jobs创建的一个类,您可以根据自己的需要对其进行修改:

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class AsyncRestClient {

    private static final String BASE_URL = "https://jobs.github.com/positions";
    private static final String JSON_RESPONSE_APPEND = ".json";
    private static final AsyncHttpClient client = new AsyncHttpClient();

    public static void getPositions(RequestParams params, AsyncHttpResponseHandler responseHandler) {
        get(JSON_RESPONSE_APPEND, params, responseHandler);
    }

    private static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }
}

以下是我使用此类的代码片段:

    RequestParams params = jobRequested.getRequestParams();
    AsyncRestClient.getPositions(params, getPositionsResponseHandler);

您需要编写自己的响应处理程序。如果你想看到所有代码,我在GitHub上有这个项目(它正处于活动开发阶段),你可以看到我如何为响应编写响应处理程序和回调:

https://github.com/JenniferVanderputten/GitHubJobs

答案 1 :(得分:0)

需要修复的两件事:

  1. 您的帖子网址链接看起来不正确:

    http://http://pathaniswaad.com/android_akshay/post.php

  2. &#34; HTTP://&#34;使用两次。将其更改为:

        http://pathaniswaad.com/android_akshay/post.php
    
    1. 您忘记将参数附加到网址:

      String data  = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");
      data += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(address, "UTF-8");
      
      link += "?"+data;  //add this line here
      
      URL url = new URL(link);
      
    2. 修复这些2然后再试一次。您还应该通过直接在浏览器中使用编制的URL来测试PHP。这样就可以确保PHP本身没有问题。

      祝你好运。