我一直试图从Web API获得成功的JSON调用,但过去几天没有成功。我尝试了多个API但没有成功,所以我不认为它是API本身,而是我用HttpURLConnection调用它。
以下是我的代码的修剪版本:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textView);
String urlString = "http://ip.jsontest.com/";
String jsonString = null;
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
Scanner scan = new Scanner(stream).useDelimiter("\\A");
jsonString = scan.next();
scan.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
textView.setText(jsonString);
}}
我已经关注并使用了多个教程和指南,试图让这个工作无济于事。我也尝试使用BufferedReader和StringBuilder来提取数据无效。
编辑:
我过去曾把它变成了一个单独的课程,但没有成功:
public class NetworkConnect {
/**
* Execute the given URI, and return the data from that URI.
*
* @param uri the universal resource indicator for a set of data.
* @return the set of data provided by the uri
*/
private Exception exception;
HttpURLConnection connection = null;
BufferedReader reader = null;
protected String doInBackground(String urlString) {
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
答案 0 :(得分:0)
只需使用AsyncTask子类,即可在后台线程上运行的doInBackground()
方法覆盖中进行网络操作。然后将结果传递给onPostExecute()
方法覆盖,该覆盖在UI线程上运行。
这是一个带有AsyncTask的简单Activity,它可以满足你的需要:
public class TestActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
textView = (TextView) findViewById(R.id.textView);
new NetworkConnect().execute();
}
class NetworkConnect extends AsyncTask<Void, Void, JSONObject> {
private static final String JSON_URL = "http://ip.jsontest.com/";
String charset = "UTF-8";
HttpURLConnection conn;
StringBuilder result;
URL urlObj;
@Override
protected JSONObject doInBackground(Void... args) {
JSONObject retObj = null;
try {
urlObj = new URL(JSON_URL);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("NetworkConnect", "result: " + result.toString());
retObj = new JSONObject(result.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return retObj;
}
@Override
protected void onPostExecute(JSONObject json) {
//Use JSON result to display in TextView
if (json != null) {
textView.setText(json.toString());
}
}
}
}
注意:确保您在AndroidManifest.xml中拥有INTERNET权限:
<uses-permission android:name="android.permission.INTERNET" />