Last active
May 11, 2024 12:36
-
-
Save hitenpratap/8e1f28d60c0bb11a5bca to your computer and use it in GitHub Desktop.
Send HTTP POST/GET request using HttpURLConnection in java
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
package com.hprog99; | |
import java.io.BufferedReader; | |
import java.io.DataOutputStream; | |
import java.io.InputStreamReader; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import javax.net.ssl.HttpsURLConnection; | |
public class HttpURLConnectionExample { | |
private final String USER_AGENT = "Mozilla/5.0"; | |
public static void main(String[] args) throws Exception { | |
HttpURLConnectionExample http = new HttpURLConnectionExample(); | |
System.out.println("GET Request Using HttpURLConnection"); | |
http.sendGet(); | |
System.out.println(); | |
System.out.println("POST Request Using HttpURLConnection"); | |
http.sendPost(); | |
} | |
// HTTP GET request | |
private void sendGet() throws Exception { | |
String username="hitenpratap"; | |
StringBuilder stringBuilder = new StringBuilder("https://twitter.com/search"); | |
stringBuilder.append("?q="); | |
stringBuilder.append(URLEncoder.encode(username, "UTF-8")); | |
URL obj = new URL(stringBuilder.toString()); | |
HttpURLConnection con = (HttpURLConnection) obj.openConnection(); | |
con.setRequestMethod("GET"); | |
con.setRequestProperty("User-Agent", USER_AGENT); | |
connection.setRequestProperty("Accept-Charset", "UTF-8"); | |
System.out.println("\nSending request to URL : " + url); | |
System.out.println("Response Code : " + con.getResponseCode()); | |
System.out.println("Response Message : " + con.getResponseMessage()); | |
BufferedReader in = new BufferedReader( | |
new InputStreamReader(con.getInputStream())); | |
String line; | |
StringBuffer response = new StringBuffer(); | |
while ((line = in.readLine()) != null) { | |
response.append(line); | |
} | |
in.close(); | |
System.out.println(response.toString()); | |
} | |
private void sendPost() throws Exception { | |
StringBuilder tokenUri=new StringBuilder("param1="); | |
tokenUri.append(URLEncoder.encode("params1","UTF-8")); | |
tokenUri.append("¶m2="); | |
tokenUri.append(URLEncoder.encode("param2","UTF-8")); | |
tokenUri.append("¶m3="); | |
tokenUri.append(URLEncoder.encode("param3","UTF-8")); | |
String url = "https://example.com"; | |
URL obj = new URL(url); | |
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); | |
con.setRequestMethod("POST"); | |
con.setRequestProperty("User-Agent", USER_AGENT); | |
con.setRequestProperty("Accept-Language", "UTF-8"); | |
con.setDoOutput(true); | |
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(con.getOutputStream()); | |
outputStreamWriter.write(params.toString()); | |
outputStreamWriter.flush(); | |
int responseCode = con.getResponseCode(); | |
System.out.println("\nSending 'POST' request to URL : " + url); | |
System.out.println("Post parameters : " + urlParameters); | |
System.out.println("Response Code : " + responseCode); | |
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); | |
String inputLine; | |
StringBuffer response = new StringBuffer(); | |
while ((inputLine = in.readLine()) != null) { | |
response.append(inputLine); | |
} | |
in.close(); | |
System.out.println(response.toString()); | |
} | |
} |
Thank you it really helped
on line 40 connection.setRequestProperty("Accept-Charset", "UTF-8");
in this line you use "connection" where is it define in code or is it a java class, if it is java class so how i get its scope?
how to open another page?????
I am unable to send the parameters still through the post request even thought i used URLencoder
any help ??
This code worked for me
URL url = new URL("https://ai.web.com/nov/index.php");
Map<String,Object> params = new LinkedHashMap<>();
params.put("accessid", "asasasasas");
params.put("uid", "sasasasa");
params.put("uname", "asasaa");
params.put("agent", "sasasasasaddd");
params.put("query", "adewewewe");
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder data = new StringBuilder();
for (int c; (c = in.read()) >= 0;) {
data.append((char)c);
}
String intentData = data.toString();
System.out.println(intentData);
I was able to post the post, but I can not read the json return in php
connect to URL
// connecting to URL
public void connectToUrl(){
doTrustToCertificates();//
URL url = new URL("https://www.example.com");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
System.out.println("ResponseCode ="+conn.getResponseCode());
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this. I was able to do my first Java send post with this :D I've added some suggestion to the comment.
Line 79: params does not exist.
Line 84: urlParameters does not exist.
With the tokenUri it's easier to read if was like this:
StringBuilder tokenUri=new StringBuilder("param1=");
tokenUri.append(URLEncoder.encode("value1","UTF-8"));
tokenUri.append("¶m2=");
tokenUri.append(URLEncoder.encode("value2","UTF-8"));
tokenUri.append("¶m3=");
tokenUri.append(URLEncoder.encode("value3","UTF-8"));
Cheers