-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpPost.java
More file actions
72 lines (57 loc) · 2.1 KB
/
HttpPost.java
File metadata and controls
72 lines (57 loc) · 2.1 KB
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
package common.android.fiot.androidcommon;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by caoxuanphong on 8/18/16.
*/
public class HttpPost {
private static final String TAG = "HttpPost";
public interface HttpPostListener {
void onPosted(String result);
}
/**
* Example: post(url, "customer_id=1&user=phong", listener)
*
* @param url
* @param urlParameters
* @param listener
*/
public void post(final String url, final String urlParameters, final HttpPostListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.i(TAG, "sendPost: " + response.toString());
listener.onPosted(response.toString());
return;
} catch (Exception e) {
e.printStackTrace();
}
listener.onPosted(null);
}
}).start();
}
}