Last active
July 25, 2018 00:28
-
-
Save renanregis/bf284f7ae8216a4d13c29e7fd842e3d0 to your computer and use it in GitHub Desktop.
POST Method example using HttpsURLConnection
This file contains hidden or 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
package com.company; | |
import javax.net.ssl.HttpsURLConnection; | |
import java.io.*; | |
import java.net.URL; | |
import java.net.URLEncoder; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
try { | |
String url = "https://example.com/api/v2"; | |
HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection(); | |
//Add request header | |
conn.setRequestMethod("POST"); | |
conn.setRequestProperty("Authorization", "Bearer " + "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiOTkxMzE5MDAyOTEiLCJkYXRhIjoiMjAxOC0wNy0yNCAxMDowOTowNSAtMDQwMCIsInJhbmRvbSI6NTg2fQ.V70gpiGkcBQqctAbSU3aqvAPVSkAC6ScX5ZIinIXb_w"); | |
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); | |
//Parameters | |
Map<String, String> parameters = new HashMap<String, String>(); | |
parameters.put("usuario", "usuario"); | |
String urlParameters = processRequestParameters(parameters); | |
//Send Post | |
conn.setDoOutput(true); | |
DataOutputStream wr = new DataOutputStream((conn.getOutputStream())); | |
wr.writeBytes(urlParameters); | |
wr.flush(); | |
wr.close(); | |
int responseCode = conn.getResponseCode(); | |
System.out.println("Sending 'POST' request to URL : " + url); | |
System.out.println("Post parameters : " + urlParameters); | |
System.out.println("Response Code : " + responseCode); | |
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); | |
String inputLine; | |
StringBuffer response = new StringBuffer(); | |
while ((inputLine = in.readLine()) != null) { | |
response.append(inputLine); | |
} | |
in.close(); | |
System.out.println(response.toString()); | |
} catch (Exception e) { | |
System.out.println(e); | |
} | |
} | |
private static String processRequestParameters(Map<String, String> parameters) throws UnsupportedEncodingException { | |
StringBuilder sb = new StringBuilder(); | |
for (String parameterName : parameters.keySet()) { | |
sb.append(parameterName).append('=').append(URLEncoder.encode(parameters.get(parameterName), "UTF-8")).append('&'); | |
} | |
return sb.substring(0, sb.length() - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment