Skip to content

Instantly share code, notes, and snippets.

@chetangani
Last active September 28, 2016 10:47
Show Gist options
  • Save chetangani/354d06d816d144c585d5befbf1e9a317 to your computer and use it in GitHub Desktop.
Save chetangani/354d06d816d144c585d5befbf1e9a317 to your computer and use it in GitHub Desktop.
Connecting URL and posting data to server..
public String PostConnection(String value) {
String response = "";
HashMap<String, String> datamap = new HashMap<>();
datamap.put("key", value);
try {
response = UrlPostConnection("URL", datamap);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public String GetConnection(String value) {
String response = "";
try {
response = UrlGetConnection("URL");
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
private String UrlPostConnection(String Url, HashMap<String, String> datamap) throws IOException {
String response = "";
URL url = new URL(Url);
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(datamap));
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="";
}
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();
}
private String UrlGetConnection(String Url) throws IOException {
String response = "";
URL url = new URL(Get_Url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
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="";
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment