gpt4 book ai didi

java - 使用post方法将android应用程序连接到网络服务器

转载 作者:行者123 更新时间:2023-11-30 22:25:27 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的 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);
?>

请提供任何形式的帮助,我们将不胜感激!!!!!!!!!!

最佳答案

有两件事需要解决:

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

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

“http://”被使用了两次。将其更改为:

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

    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);

修复这两个问题,然后重试。您还应该通过直接在浏览器中使用伪造的 url 来测试 PHP。这样它将确保 PHP 本身没有问题。

祝你好运。

关于java - 使用post方法将android应用程序连接到网络服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35380519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com