Connection. getResponseCode () is not executed during Http access in android

Source: Internet
Author: User

Problem: when android 4.4 is used to access http, connection. getResponseCode () is not executed and no error is reported. See the red font below:

Public static String getJsonContent (String url_path, String encode) {String jsonString = ""; try {URL url = new URL (url_path); HttpURLConnection connection = (HttpURLConnection) url. openConnection (); connection. setConnectTimeout (3000); connection. setRequestMethod ("GET"); connection. setDoInput (true); // get data from the server int responseCode = connection. getResponseCode (); if (200 = responseCode) {jsonString = changeInp UtStream (connection. getInputStream (), encode);} catch (Exception e) {// TODO: handle exception} // return jsonString;} private static String changeInputStream (InputStream inputStream, String encode) throws IOException {// TODO Auto-generated method stubString jsonString = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); byte [] data = new byte [1024]; int len = 0; while (len = inputSt Ream. read (data ))! =-1) {outputStream. write (data, 0, len);} jsonString = new String (outputStream. toByteArray (), encode); inputStream. close (); return jsonString ;}

This code can directly access http in a java project, and directly access urp_path = http: // 192.168.0.102: 8080/json_Project/servlet/JsonAction in a browser? Action_flag = person also corresponds to prove that the url address is correct.

Solution:

Cause: the HTTP access request is not put in a separate thread but in the main thread.

Solution: Put the http request in a new thread, or add closeStrictMode () to the onCreat () method of the Activity that calls the Http access ().


Public static void closeStrictMode (){
StrictMode. setThreadPolicy (new StrictMode. ThreadPolicy. Builder ()
. DetectAll (). penaltyLog (). build ());
}


Reference: http://hb.qq.com/a/20110914/000054.htm

Zookeeper

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.