2017-02-13 2 views
0

Я пытаюсь отправить имя и фамилию на свой сервер из приложения Android. Но не удалось установить соединение. Я использовал большинство доступных кодов, но никто из них не работает. Ниже приведен снимок моего кода:Http-запрос от приложения android к серверу

private void nextActivity(Profile profile) { 
    HttpURLConnection con = null; 

    try { 
     con = (HttpURLConnection)(new URL("**********/index.php")).openConnection();//not written the url for privacy concern 
     con.setRequestMethod("POST"); 
     con.setDoInput(true); 
     con.setDoOutput(true); 
     con.connect(); 
     con.getOutputStream().write(("name=" + profile.getFirstName()).getBytes()); 
     con.getOutputStream().write(("surname=" + profile.getLastName()).getBytes()); 
    } 
    catch (ProtocolException e) { 
     e.printStackTrace(); 
    } 
    catch (IOException e) { 
     e.printStackTrace(); 
    } 

    if (profile != null) { 
     Intent main = new Intent(LoginActivity.this, MainActivity.class); 
     main.putExtra("name", profile.getFirstName()); 
     main.putExtra("surname", profile.getLastName()); 
     main.putExtra("imageUrl", profile.getProfilePictureUri(200, 200).toString()); 
     startActivity(main); 
    } 
} 
} 
+1

Я надеюсь, что вы используете AsyncTask здесь ... –

+1

Проверка на интернет-разрешения и пробуйте пинговать сервер – VVB

+0

который исключение вы получаете? –

ответ

0

Этот код используется как AsyncTask, и моя проблема решена.

class MyAsyncTask extends AsyncTask<String, Void, String> { 

    @Override 
    protected String doInBackground(String... params) { 
     try { 
      String id = params[0], firstname = params[1], lastname = params[2]; 

      URL url = new URL("http://*******index.php"); 


      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("id", "UTF-8") + "=" + URLEncoder.encode(id, "UTF-8") + 
        "&" + URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(firstname, "UTF-8") + "&" 
        + URLEncoder.encode("surname", "UTF-8") + "=" + URLEncoder.encode(lastname, "UTF-8"); 
      bufferedWriter.write(data); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      OS.close(); 
      InputStream IS = httpURLConnection.getInputStream(); 
      IS.close(); 

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

Добавьте эти строки в свой код и попробуйте.

con.getOutputStream().flush(); 
con.getOutputStream().close(); 
+0

не работает. Приложение начало сбой –

0

Кодирование данных с использованием URLEncoder в первую очередь и запись с выходным потоком.

+0

уже пробовал. но не работает –

+0

, пожалуйста, сообщите об ошибке, которую вы получаете. –

Смежные вопросы