Android Volley API를 어떻게 사용합니까?
다음 프로젝트 ( Volley에 대한 Google IO 프레젠테이션) 에서 Android Volley 라이브러리를 구현할 생각입니다 .
그러나 해당 라이브러리에 대한 심각한 API를 찾지 못했습니다.
JSON
Volley를 사용하여 파일을 업로드하고 POST / GET 요청을 수행하고 Gson 파서를 파서로 추가하려면 어떻게해야 합니까?
편집 : 마지막으로 "Volley Library"에 대한 공식 교육입니다.
Volley 도서관에 대한 몇 가지 예를 찾았습니다.
Ognyan Bankov의 6 가지 사례 :
- 간단한 요청
- JSON 요청
- Gson 요청
- 이미지 로딩
- 최신 외부 HttpClient (4.2.3) 사용
- 자체 서명 된 SSL 인증서 사용.
Paresh Mayani의 좋은 간단한 예
HARDIK TRIVEDI의 다른 예
- ( NEW ) Ravi Tamada의 Volley Library와 함께 작동하는 Android
이것이 도움이되기를 바랍니다.
불행히도 지금까지는 JavaDocs와 같은 Volley 라이브러리에 대한 문서가 없습니다. github의 저장소와 인터넷을 통한 여러 자습서에서만 가능합니다. 따라서 유일하게 좋은 문서는 소스 코드 입니다. Volley와 놀 때이 튜토리얼을 읽었습니다 .
post / get에 대해서 당신은 이것을 읽을 수 있습니다 : Volley-POST / GET parameters
도움이 되었기를 바랍니다
Volley를 사용하여 POST 요청을 작성하는 그림입니다. StringRequest는 String 형태로 응답을 얻는 데 사용됩니다.
나머지 API가 JSON을 반환한다고 가정합니다. API의 JSON 응답은 여기에서 문자열로 수신되며 JSON으로 다시 변환하여 추가로 처리 할 수 있습니다. 코드에 주석을 추가했습니다.
StringRequest postRequest = new StringRequest(Request.Method.POST, "PUT_YOUR_REST_API_URL_HERE",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
final JSONObject jsonObject = new JSONObject(response);
// Process your json here as required
} catch (JSONException e) {
// Handle json exception as needed
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
String json = null;
NetworkResponse response = error.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode) {
default:
String value = null;
try {
// It is important to put UTF-8 to receive proper data else you will get byte[] parsing error.
value = new String(response.data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
json = trimMessage(value, "message");
// Use it for displaying error message to user
break;
}
}
loginError(json);
progressDialog.dismiss();
error.printStackTrace();
}
public String trimMessage(String json, String key){
String trimmedString = null;
try{
JSONObject obj = new JSONObject(json);
trimmedString = obj.getString(key);
} catch(JSONException e){
e.printStackTrace();
return null;
}
return trimmedString;
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("abc", "pass abc");
params.put("xyz", "pass xyz");
// Pass more params as needed in your rest API
// Example you may want to pass user input from EditText as a parameter
// editText.getText().toString().trim()
return params;
}
@Override
public String getBodyContentType() {
// This is where you specify the content type
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
// This adds the request to the request queue
MySingleton.getInstance(YourActivity.this)
.addToRequestQueue(postRequest);
// 아래는 MySingleton 클래스입니다.
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
프로젝트에 volley.jar 라이브러리를 추가하기 만하면됩니다. 그리고
Android 문서에 따라 :
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// process your response here
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//perform operation here after getting error
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
간단하게
private void load() {
JsonArrayRequest arrayreq = new JsonArrayRequest(ip.ip+"loadcollege.php",
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Album a;
try {
JSONArray data = new JSONArray(response.toString());
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
one = c.getString("cname").split(",");
two=c.getString("caddress").split(",");
three = c.getString("image").split(",");
four = c.getString("cid").split(",");
five = c.getString("logo").split(",");
a = new Album(one[0].toString(),two[0].toString(),ip.ip+"images/"+ three[0].toString(),four[0].toString(),ip.ip+"images/"+ five[0].toString());
albumList.add(a);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
@Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON array request "arrayreq" to the request queue
requestQueue.add(arrayreq);
}
위의 모든 답변을 테스트하기 전에
compile 'com.android.volley:volley:1.0.0'
gradle 파일에서 Manifest 파일에 인터넷 권한을 추가하는 것을 잊지 마십시오.
이 클래스를 사용하십시오. 데이터베이스에 쉽게 연결할 수있는 방법을 제공합니다.
public class WebRequest {
private Context mContext;
private String mUrl;
private int mMethod;
private VolleyListener mVolleyListener;
public WebRequest(Context context) {
mContext = context;
}
public WebRequest setURL(String url) {
mUrl = url;
return this;
}
public WebRequest setMethod(int method) {
mMethod = method;
return this;
}
public WebRequest readFromURL() {
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
StringRequest stringRequest = new StringRequest(mMethod, mUrl, new Response.Listener<String>() {
@Override
public void onResponse(String s) {
mVolleyListener.onRecieve(s);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
mVolleyListener.onFail(volleyError);
}
});
requestQueue.add(stringRequest);
return this;
}
public WebRequest onListener(VolleyListener volleyListener) {
mVolleyListener = volleyListener;
return this;
}
public interface VolleyListener {
public void onRecieve(String data);
public void onFail(VolleyError volleyError);
}
}
사용 예 :
new WebRequest(mContext)
.setURL("http://google.com")
.setMethod(Request.Method.POST)
.readFromURL()
.onListener(new WebRequest.VolleyListener() {
@Override
public void onRecieve(String data) {
}
@Override
public void onFail(VolleyError volleyError) {
}
});
private void userregister() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
RequestQueue queue = Volley.newRequestQueue(SignupActivity.this);
String url = "you";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pDialog.cancel();
try {
JSONObject jsonObject= new JSONObject(response.toString());
Log.e("status", ""+jsonObject.getString("status"));
if(jsonObject.getString("status").equals("success"))
{
String studentid=jsonObject.getString("id");
Intent intent=new Intent(SignupActivity.this, OTPVerificationActivity.class);
startActivity(intent);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("String ", ""+response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("password", input_password.getText().toString());
params.put("cpassword", input_reEnterPassword.getText().toString());
params.put("email", input_email.getText().toString());
params.put("status", "1");
params.put("last_name", input_lastname.getText().toString());
params.put("phone", input_mobile.getText().toString());
params.put("standard", input_reStandard.getText().toString());
params.put("first_name", input_name.getText().toString());
params.put("refcode", input_reReferal.getText().toString());
params.put("created_at","");
params.put("update_at", "");
params.put("address", input_address.getText().toString());
return params;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
참고 URL : https://stackoverflow.com/questions/17571759/how-do-you-use-the-android-volley-api
'development' 카테고리의 다른 글
ggplot에 대한 한계의 하한 만 설정 (0) | 2020.10.24 |
---|---|
Jersey에서 StreamingOutput을 응답 엔터티로 사용하는 예 (0) | 2020.10.24 |
고정 요소의 내용이 뷰포트의 높이를 초과 할 때만 스크롤 가능하게 만들려면 어떻게해야합니까? (0) | 2020.10.24 |
virtualenv에서 IPython 호출 (0) | 2020.10.24 |
@Autowired-종속성 유형의 한정 빈이 없습니다. (0) | 2020.10.24 |