Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
URL url = new URL(versionPath);
Toast.makeText(getApplicationContext(), versionPath, Toast.LENGTH_SHORT).show();
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

Toast.makeText(getApplicationContext(), "HttpURLConnection Complete!", Toast.LENGTH_SHORT).show();

Exception catched, first versionPath text is correct, cannot see the "HttpURLConnection Complete!" text. When I copy the same "versionPath" on the browser inside my device, I can see the content. I have INTERNET permission in my manifest. Any idea?

share|improve this question
1  
post ur logact here – Sam yesterday
Note: it's android.os.networkOnMainThreadException – AkariKamigishi yesterday

1 Answer

This works for me, i believe all the classes are part of android and no external libs are used.

public static JSONObject getJsonFromUrl(String urlString) throws UnsupportedEncodingException, IllegalStateException, IOException, JSONException {
    // set the connection timeout value to 10 seconds (10000 milliseconds)
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 10000); //how long to wait for connection
    HttpConnectionParams.setSoTimeout(httpParams, 10000); //how long to wait for response
    // Create a new HTTP Client
    DefaultHttpClient defaultClient = new DefaultHttpClient(httpParams);
    // Setup the get request
    HttpGet httpGetRequest = new HttpGet(urlString);
    // Execute the request in the client
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
    // Grab the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
    StringBuilder json = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        json.append(line);
    }

    // Instantiate a JSON object from the request response
    JSONObject jsonObject = new JSONObject(json.toString());

    return jsonObject;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.