btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) { new JsonParse().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItems.txt");}});}
public class JsonParse extends AsyncTask<String,String,String>
@Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try { URI url = new URI(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer stringBuffer = new StringBuffer();
String linge = "";
while ((linge = reader.readLine()) != null) {
stringBuffer.append(linge);}
return stringBuffer.toString(); } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {if (connection != null){connection.disconnect();try {
if (reader != null) { reader.close();}} catch (IOException e) {e.printStackTrace(); }}return null } @Override
protected void onPostExecute(String result{super.onPostExecute(result);
tv.setText(result);} }}
答案 0 :(得分:1)
很难读取您的代码,但下面是您如何使用HttpURLConnection
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4");
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setInstanceFollowRedirects(false);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
或者还有另一种方法
URL url = new URL(uri);
stream = url.openStream();
br = new BufferedReader(new InputStreamReader(stream));
现在使用while ((line = br.readLine()) != null)