1 Replies - 284 Views - Last Post: 27 October 2015 - 04:50 PM

#1 TheRookie   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 45
  • Joined: 31-August 14

Application crashes when trying to send json http post

Posted 27 October 2015 - 04:18 PM

The application chrashes when I try to call this function on the onCreate method.
I do not have an application Log.
public void HttpPost() {
		try {

			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost post = new HttpPost("https://api.website.net/auth/token");

			StringEntity input = new StringEntity( "{\"auth\":{\"user\": {\"id\": \"user\",\"password\": \"user\"},\"method\": \"user\",\"website\": \"website.net\"}}");
			post.setEntity(input);
			post.setHeader("Accept", "application/json");
			post.setHeader("Content-Type","application/json");

			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				System.out.println(line);
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}



Thank you!

Is This A Good Question/Topic? 0
  • +

Replies To: Application crashes when trying to send json http post

#2 EndLessMind   User is offline

  • Android Expert
  • member icon

Reputation: 273
  • View blog
  • Posts: 1,252
  • Joined: 13-March 09

Re: Application crashes when trying to send json http post

Posted 27 October 2015 - 04:50 PM

Networking is not allowed on the main thread (UI thread).
Call it from within an other thread and you'll be fine.


 
new Thread(new Runnable() {
    public void run() {
      HttpPost();
    }
  }).start();


This post has been edited by EndLessMind: 27 October 2015 - 04:53 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1