Created
May 11, 2016 10:24
-
-
Save roshanpal/3eda3773110cb23d808f49b4c65379fc to your computer and use it in GitHub Desktop.
HttpPost AsyncTask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private class UploadTask extends AsyncTask<String, Void, String> { | |
@Override | |
protected String doInBackground(String... params) { | |
HashMap<String, String> postData = new HashMap<>(); | |
postData.put("image", params[0]); | |
String t = performPostCall("http://examxple.com/upload.php", postData); | |
Log.d("TUNA", t); | |
return null; | |
} | |
public String performPostCall(String requestURL, HashMap<String, String> postDataParams) { | |
URL url; | |
String response = ""; | |
try { | |
url = new URL(requestURL); | |
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); | |
conn.setReadTimeout(15000); | |
conn.setConnectTimeout(15000); | |
conn.setRequestMethod("POST"); | |
conn.setDoInput(true); | |
conn.setDoOutput(true); | |
OutputStream os = conn.getOutputStream(); | |
BufferedWriter writer = new BufferedWriter( | |
new OutputStreamWriter(os, "UTF-8")); | |
writer.write(getPostDataString(postDataParams)); | |
writer.flush(); | |
writer.close(); | |
os.close(); | |
int responseCode=conn.getResponseCode(); | |
if (responseCode == HttpsURLConnection.HTTP_OK) { | |
String line; | |
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
while ((line=br.readLine()) != null) { | |
response+=line; | |
} | |
} | |
else { | |
response=""; | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
return response; | |
} | |
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{ | |
StringBuilder result = new StringBuilder(); | |
boolean first = true; | |
for(Map.Entry<String, String> entry : params.entrySet()){ | |
if (first) | |
first = false; | |
else | |
result.append("&"); | |
result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); | |
result.append("="); | |
result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); | |
} | |
return result.toString(); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment