java - 在 PHP 页面上发送字符串的方法

标签 java android httprequest

我正在尝试有关“如何将字符串发送到 PHP 页面”的不同教程。 我尝试过的这个似乎是学习一些东西的最佳解决方案。 该应用程序编译时没有错误,但在我的设备上似乎没有向 php 页面发送任何内容。 我在AndroidManifest.xml上授予权限

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

TextView content;
EditText fname,email,login,pass;
String Name,Email,Login,Pass;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    content = (TextView)findViewById(R.id.content);
    fname   =(EditText)findViewById(R.id.name);
    email   =(EditText)findViewById(R.id.email);
    login   =(EditText)findViewById(R.id.loginname);
    pass    =(EditText)findViewById(R.id.password);


    Button saveme=(Button)findViewById(R.id.save);
    saveme.setOnClickListener(new Button.OnClickListener(){
        public void onClick(View v)
        {
            try{

                GetText();
            }
            catch(Exception ex)
            {
                content.setText("url exeption!");
            }
        }
    });
}


public void GetText() throws UnsupportedEncodingException
{

    Name    = fname.getText().toString();
    Email   = email.getText().toString();
    Login   = login.getText().toString();
    Pass    = pass.getText().toString();



    String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(Name, "UTF-8");
    data += "&" + URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(Email, "UTF-8");
    data += "&" + URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(Login, "UTF-8");
    data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode(Pass, "UTF-8");

    String text = "";
    BufferedReader reader=null;
    // Send data
    try
    {

        URL url = new URL("http://thingsforcoins.com/receive/httppost.php");

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();
        // Get the response


        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;


        while((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        text = sb.toString();
    }
    catch(Exception ex)
    {

    }
    finally
    {
        try
        {

            reader.close();
        }
        catch(Exception ex) {}
    }

    content.setText(text);

}

}

该应用程序读取四个编辑文本字段,并将数据保存在应发送到 PHP 页面并显示数据的字符串中。

最佳答案

我认为你应该这样做:

        byte[] postData = data.getBytes(Charset.forName("UTF-8"));
        int postDataLength = postData.length;
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Charset", "utf-8");
        conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
        conn.setUseCaches(false);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);
        wr.close();
        if (conn.getResponseCode() == 200) {
            //...
        } else {
            //...
        }

哪里data是你的String data = URLEncoder.encode("name", "UTF-8") + ... 还有代码行conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");可能不需要。

关于java - 在 PHP 页面上发送字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46621457/

相关文章:

wcf - 发送到 WCF 服务时在 Soap 信封中使用 json 正文

java - 如何使用 java.net.URLConnection 来触发和处理 HTTP 请求

java - 我在 Android Studio 的谷歌地图中得到零经度和纬度值

java - XJC [错误] "//*[local-name()=' 架构的 XPath 评估']“导致目标节点为空

java - 无法在 JNI 中编码为 UTF-8

java - 相机预览 View ,水平,而应该是垂直 在 HTC Tattoo 上工作正常,在 Nexus 上坏了

android - 将文件从我的 res/raw 文件夹下载(复制?)到默认的 Android 下载位置?

php - 我可以在 PHP 中禁用 DNS 查找吗?我有 IP 地址和主机名

Java 9 模块系统资源文件位置

java - 如何使用构造函数设置不在构造函数内部的其他字段