Reputation: 100
I'm trying to get json data from node js server that runs on my pc. My pc and the phone that runs this app are connected via Wifi to the same router. Here is the json:
{"name":"Jon Snow","address":"Winterfell","occupation":"Knows nothing"}
Here is MainActivity class:
public class MainActivity extends AppCompatActivity {
TextView nameLabel;
TextView addressLabel;
TextView occupationLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameLabel = findViewById(R.id.nameLabel);
addressLabel = findViewById(R.id.addressLabel);
occupationLabel = findViewById(R.id.occupationLabel);
serverReader();
}
@SuppressLint("StaticFieldLeak")
private void serverReader() {
new AsyncTask<Void, Void, Student>() {
@Override
protected Student doInBackground(Void... voids) {
try {
StringBuilder parsedString = new StringBuilder();
URL url = new URL("192.168.31.113:8080");
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
InputStream is = httpConn.getInputStream();
Scanner sc = new Scanner(is);
while(sc.hasNext()){
parsedString.append(sc.nextLine());
}
sc.close();
is.close();
JSONObject jsonStudent = new JSONObject(parsedString.toString());
return new Student(jsonStudent.getString("name"),
jsonStudent.getString("address"),
jsonStudent.getString("occupation"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(Student student) {
if(student != null)Student.displayStudent(student, nameLabel, addressLabel, occupationLabel);
}
}.execute();
}
}
App throws exception on line URL url = new URL("192.168.31.113:8080");
. I am a little confused.
I tried to open this url in browser and it worked perfectly. What should I change in my code?
Upvotes: 0
Views: 80
Reputation: 3372
As others stated you need to add the protocol to your url...
Also you may wish to consider using VOLLEY in your Android app over the low level http calls.. just a thought.
Upvotes: 0
Reputation: 26
Try to provide the full url instead of <domain>:<port>
:
http://192.168.31.113:8080/
Upvotes: 1