没有收到服务器的任何回应

时间:2019-04-12 06:05:20

标签: android connection wamp

我试图将值插入MySql服务器,但是什么也没发生。

这是我的代码。

 @Override
    protected String doInBackground(String... strings) {
        String reg_url="http://192.168.43.198:80/android_connect/insert_to_profile_table.php";
        String f_name = first_name.getText().toString();
        String l_name = last_name.getText().toString();
        String address = p_address.getText().toString();
        String phne_hme = phne_home.getText().toString();
        String phne_ofice = phne_office.getText().toString();
        String State = state_spinner.getSelectedItem().toString();
        String district = district_spinner.getSelectedItem().toString();
                   try {
                    URL url=new URL(reg_url);
                    HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    OutputStream os=httpURLConnection.getOutputStream();

                    BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));

                    String data= URLEncoder.encode("first_name","UTF-8")+"="+URLEncoder.encode(f_name,"UTF-8")+"&"+
                            URLEncoder.encode("last_name","UTF-8")+"="+URLEncoder.encode(l_name,"UTF-8")+"&"+
                            URLEncoder.encode("address","UTF-8")+"="+URLEncoder.encode(address,"UTF-8")+"&"+
                            URLEncoder.encode("state","UTF-8")+"="+URLEncoder.encode(State,"UTF-8")+"&"+
                            URLEncoder.encode("district","UTF-8")+"="+URLEncoder.encode(district,"UTF-8")+"&"+
                            URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(phne_hme,"UTF-8");
                    //System.out.print(data.toString());
                    bufferedWriter.write(data);
                    bufferedWriter.flush();
                    bufferedWriter.close();
                    os.close();
                    InputStream IS=httpURLConnection.getInputStream();
                    IS.close();
                    return "Registration Successful";


                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
    }

Logcats

  

D / WindowClient:添加到mViews:DecorView @ ef0b228 [],此= android.view.WindowManagerGlobal@6d9edde   D / OpenGLRenderer:CanvasContext()0x95130800   D / ViewRootImpl [Profile_add]:启用了硬件加速,这= ViewRoot {4906488 com.indiamission.mission / com.indiamission.mission.Profile_add,ident = 4}   I / System.out:[套接字] [1]连接/192.168.43.198:80;LocalPort=-1(0)   D /:[Posix_connect调试]进程com.indiamission.mission:80   I / art:输入while循环。   D /曲面:Surface :: allocateBuffers(this = 0x957f9c00)   D / OpenGLRenderer:CanvasContext()0x95130800初始化窗口= 0x957f9c00,标题= com.indiamission.mission / com.indiamission.mission.Profile_add   D /曲面:Surface :: connect(this = 0x957f9c00,api = 1)   W / libEGL:[ANDROID_RECORDABLE]格式:1   D / mali_winsys:EGLint new_window_surface(egl_winsys_display *,void *,EGLSurface,EGLConfig,egl_winsys_surface **,egl_color_buffer_format *,EGLBoolean)返回0x3000   D / OpenGLRenderer:〜CanvasContext()0x9512d000   D / GraphicBuffer:寄存器,句柄(0x95177600)(w:552 h:270 s:560 f:0x1 u:0x000b00)   D / GraphicBuffer:寄存器,句柄(0x95177780)(w:552 h:270 s:560 f:0x1 u:0x000b00)   D / GraphicBuffer:寄存器,句柄(0x95177840)(w:552 h:270 s:560 f:0x1 u:0x000b00)   I / System.out:[套接字] [/ 192.168.43.222:40230]已连接   I / System.out:检查isMmsSendPdu       PDU读取len:8192       MMS PDU类型:102:105   I / System.out:[OkHttp] sendRequest >>   I / System.out:[OkHttp] sendRequest <<< / p>

什么也没有发生。谢谢大家。

2 个答案:

答案 0 :(得分:0)

String ServerURL = "your_php_file_url" ;
EditText first_name, last_name,p_address,phne_home,phne_office ;
Button button;
Spinner state_spinner,district_spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity_name);
    /*==================================================================
                Bind Your spinners and Edittext with the IDs Here
    ====================================================================*/

    fname = (EditText)findViewById(R.id.fname);

    /*==================================================================
                Bind Your spinners and Edittext with the IDs ABove ^^^
    ====================================================================*/

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            GetData();

            InsertData(f_name,l_name,address,phne_hme,phne_ofice,State,district);

        }
    });
}

public void GetData(){

    String f_name = first_name.getText().toString();
    String l_name = last_name.getText().toString();
    String address = p_address.getText().toString();
    String phne_hme = phne_home.getText().toString();
    String phne_ofice = phne_office.getText().toString();
    String State = state_spinner.getSelectedItem().toString();
    String district = district_spinner.getSelectedItem().toString();

}

public void InsertData(final String fname, final String lname,final String address,final String phne_hme, final String phn_ofice, final String State, final String district){

    class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
        String f_nameHolder = fname;
        String l_nameHolder = lname;
        String addressHolder = address;
        String phne_hmeHolder = phne_hme;
        String phne_oficeHolder = phne_ofice;
        String StateHolder = State;
        String districtHolder = district;

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", f_nameHolder));
            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files",l_nameHolder));
            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", addressHolder));
            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", phne_hmeHolder));
            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", phne_oficeHolder));
            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", StateHolder));
            nameValuePairs.add(new BasicNameValuePair("replace these names with your key given in PHP files", districtHolder));


            try {
                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost(ServerURL);

                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();


            } catch (ClientProtocolException e) {

            } catch (IOException e) {

            }
            return "Data Inserted Successfully";
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

        }
    }

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

    sendPostReqAsyncTask.execute(fname,lname,address,phne_hme,phn_ofice,State,district);
}

别忘了在gradle文件中添加Org.Apache.Http.Legacy此依赖项。

答案 1 :(得分:0)

我使用此link正确了。

 @Override
    protected String doInBackground(String... strings) {

        String f_name = first_name.getText().toString();
        String l_name = last_name.getText().toString();
        String address = p_address.getText().toString();
        String phne_hme = phne_home.getText().toString();
        String phne_ofice = phne_office.getText().toString();
        String State = state_spinner.getSelectedItem().toString();
        String district = district_spinner.getSelectedItem().toString();
        String email_ = email.getText().toString();

        HttpURLConnection conn;
        URL url = null;
        try {
            // Enter URL address where your php file resides
            url = new URL(getString(R.string.link)+"insert_to_profile_table.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            OutputStream os=conn.getOutputStream();
            BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            String data= URLEncoder.encode("first_name","UTF-8")+"="+URLEncoder.encode(f_name,"UTF-8")+"&"+
                    URLEncoder.encode("last_name","UTF-8")+"="+URLEncoder.encode(l_name,"UTF-8")+"&"+
                    URLEncoder.encode("address","UTF-8")+"="+URLEncoder.encode(address,"UTF-8")+"&"+
                    URLEncoder.encode("state","UTF-8")+"="+URLEncoder.encode(State,"UTF-8")+"&"+
                    URLEncoder.encode("district","UTF-8")+"="+URLEncoder.encode(district,"UTF-8")+"&"+
                    URLEncoder.encode("phone_number1","UTF-8")+"="+URLEncoder.encode(phne_hme,"UTF-8")+"&"+
                    URLEncoder.encode("phone_number2","UTF-8")+"="+URLEncoder.encode(phne_ofice,"UTF-8")+"&"+
                    URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email_,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            os.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }
        try {
            int response_code = conn.getResponseCode();
            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {
                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return (result.toString());
            } else {
                return ("unsuccessful");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }
    }
    @Override
    protected void onPostExecute(String result) {
        pDialog.dismiss();
        if(result.equals("Success! This message is from PHP")) {
            Toast.makeText(Profile_add.this, result.toString(), Toast.LENGTH_LONG).show();
        }else{
            // you to understand error returned from doInBackground method
            Toast.makeText(Profile_add.this, result.toString(), Toast.LENGTH_LONG).show();
        }
    }