【问题标题】:why httpurlconnection is not executing?为什么 httpurlconnection 没有执行?
【发布时间】:2019-01-07 08:23:28
【问题描述】:

我正在从 android 向 php 服务器发送一些数据。但是 httpurlconnection 不起作用。我认为我的网址没有发生连接。因为我的电脑不支持模拟,所以在我的手机中测试我的构建 apk 时,我无法调试我的代码。我在执行时检查 toast,但连接后它既不显示 CONNECTED 也不显示 NOT CONNECTED toast。我的 url 连接代码有什么问题,还是我必须在我的 php 服务器端做一些事情才能接受来自 android 应用程序的连接?

package com.it.jumtech.equestion;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {

Button button_login;
EditText edit_uid,edit_pwd;
AlertDialog.Builder builder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    button_login = (Button)findViewById(R.id.button_login);
    edit_uid = (EditText)findViewById(R.id.edit_uid);
    edit_pwd = (EditText)findViewById(R.id.edit_pwd);
    builder = new AlertDialog.Builder(this);
    // onclick button this function will execute
    button_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("uid", edit_uid.getText().toString());
                jsonObject.put("pwd", edit_pwd.getText().toString());
                String logininfo = jsonObject.toString();
                Toast.makeText(LoginActivity.this,
                        "Json Built = " + logininfo, Toast.LENGTH_LONG).show();
                String link = "http://www.example.com/login_chk.php";
                URL url = new URL(link);
                HttpURLConnection conn = null;
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    Toast.makeText(LoginActivity.this,
                            "Connected", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(LoginActivity.this,
                            "Not Connected", Toast.LENGTH_LONG).show();
                }
                OutputStream os = conn.getOutputStream();
                Toast.makeText(LoginActivity.this,
                        "ostream made", Toast.LENGTH_LONG).show();
                BufferedWriter bw = new BufferedWriter(new
                        OutputStreamWriter(os,"UTF-8"));
                String data  = URLEncoder.encode("param_logininfo", "UTF-8") + "=" +
                        URLEncoder.encode(logininfo, "UTF-8");
                bw.write(data);
                Toast.makeText(LoginActivity.this,
                        data+"written to url", Toast.LENGTH_LONG).show();
                bw.flush();
                bw.close();
                os.close();
                Toast.makeText(LoginActivity.this,
                        "Json Sent", Toast.LENGTH_LONG).show();
                int respcode = conn.getResponseCode();
                Toast.makeText(LoginActivity.this,
                        "Response code = "+respcode, Toast.LENGTH_LONG).show();
                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new
                        InputStreamReader(is,"UTF-8"));
                StringBuffer sb = new StringBuffer();
                String line = null;
                // read server output
                Toast.makeText(LoginActivity.this,
                        "Read from server", Toast.LENGTH_LONG).show();
                while((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                String result = sb.toString();
                Toast.makeText(LoginActivity.this,
                        "Success return from server", Toast.LENGTH_LONG).show();
                Toast.makeText(LoginActivity.this,
                        result, Toast.LENGTH_LONG).show();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}
}

【问题讨论】:

  • 你不能在主线程上做网络工作。
  • @Henry 你刚才说什么?解释一下。
  • Android 不允许在 UI(主)线程上进行联网,因为这可能会阻塞 UI。您需要在单独的线程上执行此操作。另见stackoverflow.com/questions/6343166/…

标签: java android httpurlconnection


【解决方案1】:

您需要添加特殊权限才能发送 HTTP 请求。 Android 默认会阻止简单的 HTTP,因为它们被认为不安全。

您的清单应包含:

<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

如果你没有设置这个权限,android 会抛出一个IOException

另外,你好像在主线程上做网络,这是不允许的。

使用工作线程或AsyncTask 进行阻塞操作,例如 HTTP 请求。

【讨论】:

  • 有互联网权限。好的,我会尝试异步任务。
  • 你能帮我写代码吗?一些示例代码展示了如何在 asynctask 中编写连接。
  • @user3099225 看看这里:medium.com/@lewisjkl/…
猜你喜欢
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-15
  • 1970-01-01
相关资源
最近更新 更多