Получение страницы по http протоколу на Android
Задача: получить «сырой» json по протоколу http в приложении под андроид.
Решение:
1) Разрешим доступ в интернет в AndroidManifest.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ru.erver.noc.nocmessages"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <application android:resource="@xml/netsec" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.NoActionBar" > <activity android:name=".Form1"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
2) Код:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
package ru.yarteleservice.noc.nocmessages; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Form1 extends AppCompatActivity { EditText logv; jsonnoc jsn; public void AddToLog(String txt) { logv = (EditText) findViewById(R.id.editText3); if (txt == "clear") { logv.setText(""); } else { logv.append(txt); logv.append("\n"); } ; } ; public void ClickEnterNocButton(View view) { Log.d("неашипка", "--click!"); AddToLog("clear"); EditText elogin = (EditText) findViewById(R.id.editText); EditText epass = (EditText) findViewById(R.id.editText2); AddToLog("-пробуем залогиниться"); // jsonnoc jsn=new jsonnoc(); //jsn.GetJsonMet("{'userlogin':'login'}"); new GetMyDataFromUrl().execute("!!!!!!!!!"); AddToLog("-сохраняем настройки"); SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor mEdit = mSettings.edit(); mEdit.putString("userlogin", elogin.getText().toString()); mEdit.commit(); mEdit.apply(); mEdit.putString("userpass", epass.getText().toString()); mEdit.commit(); mEdit.apply(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_form1); AddToLog("-читаем настройки"); EditText elogin = (EditText) findViewById(R.id.editText); EditText epass = (EditText) findViewById(R.id.editText2); SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); elogin.setText(mSettings.getString("userlogin", "")); epass.setText(mSettings.getString("userpass", "")); AddToLog(elogin.getText().toString()); AddToLog(epass.getText().toString()); } class GetMyDataFromUrl extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... arg) { String res; BufferedReader reader = null; String resultJson = ""; res=null; HttpURLConnection urlConnection = null; Log.d("неашипка", "--пробую почитать json"); try { URL url = new URL("http://noc.dfvdfv.ru/getjsonmess.php"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); Log.d("неашипка", resultJson); } catch (Exception e) { e.printStackTrace(); Log.d("ашипка", "--не смогли прочитать JSON"); } return res; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } } } |
Результат: