forked from javadghane/simple-Android-Server-communicator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncPostDataWithOkHttp.java
81 lines (58 loc) · 1.9 KB
/
AsyncPostDataWithOkHttp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import android.os.AsyncTask;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* Created by JavaDroid.ir on 4/17/2015.
*/
public class AsyncPostData extends AsyncTask<HashMap, Void, String> {
private String link = "";
String response = "";
public AsyncResponse delegate = null;
public static interface AsyncResponse {
void processFinish(String output);
}
public AsyncPostData(
String link, AsyncResponse list) {
this.link = link;
this.delegate = list;
}
protected void onPreExecute() {
}
@Override
protected String doInBackground(HashMap... maps) {
OkHttpClient client = new OkHttpClient();
MultipartBody.Builder form = new MultipartBody.Builder();
form.setType(MultipartBody.FORM);
Set set = maps[0].entrySet();
for (Object aSet : set) {
Map.Entry me = (Map.Entry) aSet;
form.addFormDataPart(me.getKey().toString(), me.getValue().toString());
}
RequestBody requestBody = form.build();
Request request = new Request.Builder()
.url(this.link)
.method("POST", RequestBody.create(null, new byte[0]))
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
response = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
if (delegate != null)
delegate.processFinish(result);
}
}