如何使用 HttpURLConnection 而不是 Volley 获取 JSON 对象?
How to get JSON object using HttpURLConnection instead of Volley?
我想做的是从 HttpURLConnection
中获取一些数据,而不是使用 Volley 库中的 JsonObjectRequest()
。
下面是我用来从服务器获取 JSON 对象的代码。
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,"myURL", null, new Response.Listener<JSONObject>();
在 myURL
更改为 null
后,我尝试将 null
更改为 JSONObject
。但这并没有成功。
JsonObjectRequest()
中的url不可选,JSONObject参数用于post参数随请求到url.
来自文档:
http://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html
http://developer.android.com/training/volley/index.html
JsonObjectRequest
public JsonObjectRequest(int method,
String url,
JSONObject jsonRequest,
Response.Listener listener,
Response.ErrorListener errorListener) Creates a new request.
Parameters:
method - the HTTP method to use
url - URL to fetch the JSON from
jsonRequest - A JSONObject to post with the request. Null is allowed
and indicates no parameters will be posted along with request.
listener - Listener to receive the JSON response
errorListener - Error listener, or null to ignore errors.
使用HttpURLConnection
:
http://developer.android.com/reference/java/net/HttpURLConnection.html
代码应该是这样的:
public class getData extends AsyncTask<String, String, String> {
HttpURLConnection urlConnection;
@Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://api.github.com/users/dmnugent80/repos");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
//Do something with the JSON string
}
}
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MyAsyncTask extends AsyncTask<URL, Void, String> {
private HttpURLConnection urlConnection;
private Context mContext;
private ProgressDialog mDialog;
private TaskListener mListener;
public MyAsyncTask(Context context, TaskListener listener) {
this.mContext = context;
mDialog = new ProgressDialog(mContext);
this.mListener = listener;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setTitle(R.string.app_name);
mDialog.setMessage("Retrieving data...");
mDialog.show();
}
@Override
protected String doInBackground(URL... params) {
StringBuilder result = new StringBuilder();
try {
URL url = params[0];
// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
urlConnection = (HttpURLConnection) url.openConnection(/*proxy*/);
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(20 * 1000);
urlConnection.setReadTimeout(20 * 1000);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mDialog.dismiss();
mListener.onTaskComplete(s);
}
}
使用这个功能
private String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-Type", "application/json; utf-8");
c.setRequestProperty("Accept", "application/json");
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
我想做的是从 HttpURLConnection
中获取一些数据,而不是使用 Volley 库中的 JsonObjectRequest()
。
下面是我用来从服务器获取 JSON 对象的代码。
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,"myURL", null, new Response.Listener<JSONObject>();
在 myURL
更改为 null
后,我尝试将 null
更改为 JSONObject
。但这并没有成功。
JsonObjectRequest()
中的url不可选,JSONObject参数用于post参数随请求到url.
来自文档: http://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html
http://developer.android.com/training/volley/index.html
JsonObjectRequest
public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener listener, Response.ErrorListener errorListener) Creates a new request.
Parameters:
method - the HTTP method to use
url - URL to fetch the JSON from
jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request.
listener - Listener to receive the JSON response
errorListener - Error listener, or null to ignore errors.
使用HttpURLConnection
:
http://developer.android.com/reference/java/net/HttpURLConnection.html
代码应该是这样的:
public class getData extends AsyncTask<String, String, String> {
HttpURLConnection urlConnection;
@Override
protected String doInBackground(String... args) {
StringBuilder result = new StringBuilder();
try {
URL url = new URL("https://api.github.com/users/dmnugent80/repos");
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}catch( Exception e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return result.toString();
}
@Override
protected void onPostExecute(String result) {
//Do something with the JSON string
}
}
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MyAsyncTask extends AsyncTask<URL, Void, String> {
private HttpURLConnection urlConnection;
private Context mContext;
private ProgressDialog mDialog;
private TaskListener mListener;
public MyAsyncTask(Context context, TaskListener listener) {
this.mContext = context;
mDialog = new ProgressDialog(mContext);
this.mListener = listener;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mDialog.setTitle(R.string.app_name);
mDialog.setMessage("Retrieving data...");
mDialog.show();
}
@Override
protected String doInBackground(URL... params) {
StringBuilder result = new StringBuilder();
try {
URL url = params[0];
// Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
urlConnection = (HttpURLConnection) url.openConnection(/*proxy*/);
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(20 * 1000);
urlConnection.setReadTimeout(20 * 1000);
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return result.toString();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
mDialog.dismiss();
mListener.onTaskComplete(s);
}
}
使用这个功能
private String getJSON(String url) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-Type", "application/json; utf-8");
c.setRequestProperty("Accept", "application/json");
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), "utf-8"));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}