我在排球时使用GET请求:
HTTPRequest.java
public void get(String url) {
// Request a string response from the provided URL.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
getReponse(), createMyReqErrorListener()) {
@Override
protected void deliverResponse(JSONObject response) {
Log.d(TAG, "deliverResponse= " + response.toString());
super.deliverResponse(response);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
headers.put(ACCEPT, ACCEPT_JSON);
headers.put(AUTH_ID, AUTH_ID_VALUE);
headers.put(PLATFORM, PLATFORM_VALUE);
headers.put(CID, "");
System.out.println(headers.toString());
return headers;
}
};
// Add the request to the RequestQueue.
queue.add(request);
}
从下面的网址中获取JSON是JSON(虚拟内容)的一个示例:
远程服务器上的JSON文件
{
"Errors": null,
"Session": {
"SessionId": ""
},
"someUrl": "http://www.someurl.com",
"BlockPromotions": {
"@CategoryId": "1",
"Type": "PAGE",
"Items": {
"Item": [
{
"@Id": "2",
"DisplayImage": "http://imageurl/something.png",
"DisplayOrder": "1"
},
{
"@Id": "3",
"DisplayImage": "http://imageurl/something_else.png",
"DisplayOrder": "2"
}
]
}
}
}
我用来解析JSON的代码如下:
Parser.java
public String parseResponse(JSONObject response) {
try {
JSONObject objectBlockPromo = response.getJSONObject("BlockPromotions");
JSONObject objectItems = objectBlockPromo.getJSONObject("Items");
JSONArray arrayItem = objectItems.getJSONArray("Item");
for (int i = 0; i < arrayItem.length(); i++) {
JSONObject item = arrayItem.getJSONObject(i);
ImageURL = item.getString("DisplayImage");
System.out.println(ImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
return ImageURL;
}
我设法单独抓取所有网址,我的问题是将这些网址重新交给HomeScreen,以显示图片?
我该怎么做?
我已尝试将URL用作String,我也尝试使用Volley的ImageRequest获取URL(但我认为我做错了)。
由于
答案 0 :(得分:0)
您需要打开与URL的连接,下载图像然后再显示它。
String name = "yourdesiredfilename";
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
OutputStream output = openFileOutput(name, MODE_PRIVATE);
IOUtils.copy(input, output);
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
(我只是因为我很懒;)) 然后你在本地拥有该文件,并可以将它传递给ImageView或任何你拥有的文件。
Drawable d = Drawable.createFromPath(pathName);
ImageView yourView;
yourView.setImageDrawable(d);
答案 1 :(得分:0)