Simple POST request/response method? - java

Basically, all I want to do is get the text response of a PHP page with some POST variables I define.
So, what is the easiest way of sending some POST data (like "arg1=this&arg2=that") to a URL and handling the response (content, not headers) as a string?

Use HttpUrlConnection to send a post request using java. attach your all parameter and in test.php prepare your response and return back to sender.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
private void sendPost() throws Exception
{
String url = "http://example.com/test.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0";);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "para1= xxx & para2=yy";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
if(responseCode == HTTP_OK)
{
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();
//print result
System.out.println(response.toString());
}
}

Related

Send GET request with token using Java HttpUrlConnection

I have to work with RESTful web service which uses token-based authentication from Java application. I can successfully get token by this way:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public void getHttpCon() throws Exception{
String POST_PARAMS = "grant_type=password&username=someusrname&password=somepswd&scope=profile";
URL obj = new URL("http://someIP/oauth/token");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Authorization",
"Basic Base64_encoded_clientId:clientSecret");
con.setRequestProperty("Accept",
"application/x-www-form-urlencoded");
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}
But I cannot find a way to properly send this token in the get request. What I'm trying:
public StringBuffer getSmth(String urlGet, StringBuffer token) throws IOException{
StringBuffer response = null;
URL obj = new URL(urlGet);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
String authString = "Bearer " + Base64.getEncoder().withoutPadding().encodeToString(token.toString().getBytes("utf-8"));
con.setRequestProperty("Authorization", authString);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
System.out.println("GET request not worked");
}
return response;
}
doesn't work. Any help to solve this problem will be highly appreciated.
Solved. Server returns some extra strings besides token itself. All I had to do is to extract pure token from the received answer and paste it without any encoding: String authString = "Bearer " + pure_token;
You should add the token to request url:
String param = "?Authorization=" + token;
URL obj = new URL(urlGet + param);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
conn.setRequestMethod("GET");
As an alternative, use restTemplate to send a get request:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + token);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(urlGet, HttpMethod.GET, request, String.class);

How to call SOAP web services from JAVA

I want to know that how we can call SOAP web services from GET and POST request from java program.
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("Testing 1 - Send Http GET request");
//http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://http://localhost/getmiweb/public/api/v1/OrderAPI";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
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();
//print result
System.out.println(response.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://http://localhost/getmiweb/public/api/v1/OrderAPI";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
//Passing Parameters
String urlParameters = "token=t0ocgQ/jj8YbjasuLYJ12KJoZmaLNt4zUcEZZKxCU6E=&orderId=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
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();
//print result
System.out.println(response.toString());
}
}

Trying to HTTP POST But Getting MalformedURLException: no protocol: yahoo.com

Overall I'm trying to write a script that captures the servers' response to an HTTP POST using java.
Unfortunately, I'm stuck at encoding the URL portion of it. While I followed several online example on encoding a URL, I still get MalformedURLException...
Any idea what might go wrong in the encoding process?
The error:
$ java client_post
Sending Http POST request
Exception in thread "Main Thread" java.net.MalformedURLException: no
protocol: http%3A%2F%2Fyahoo.com
at java.net.URL.<init>(URL.java:567)
at java.net.URL.<init>(URL.java:465)
at java.net.URL.<init>(URL.java:414)
at client_post.sendPost(client_post.java:30)
at client_post.main(client_post.java:23)
The code:
//package client_post;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class client_post {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
client_post http = new client_post();
System.out.println("\nSending Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
//String url =<host:port/create/service>
String url = "http://yahoo.com";
String EncoderUrl = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(EncoderUrl);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
String urlParameters = "<string base64>";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
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();
//print result
System.out.println(response.toString());
System.out.println(response.toString());
}
}
When you are encoding url your url becomes like below
http%3A%2F%2Fyahoo.com
Dont encode untill you have something special in it.
Your programm is also throwing class cast exception
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Above should be like below
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
Below is working programm.
package com.ds.portlet.library;
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 client_post {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
client_post http = new client_post();
System.out.println("\nSending Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
//String url =<host:port/create/service>
String url = "http://yahoo.com";
// String EncoderUrl = URLEncoder.encode(url, "UTF-8");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language","en-US,en;q=0.5");
String urlParameters = "<string base64>";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
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();
//print result
System.out.println(response.toString());
System.out.println(response.toString());
}
}
It looks like you're trying to encode the entire URL, including the :// and similar characters. The purpose of URL encoding is to hide those characters in a path or query part, and they shouldn't be encoded in the main URL. Use URLEncoder only for parameters or application/x-www-form-urlencoded contents.

Java code giving error,: Syntax error or token "1", < expected

i am trying to make an HTTP POST request to Hackerrank API but the code is not compiling and giving the error Syntax error or token "1", < expected. One of the POST parameters is 'testcase' which needs to be a string but this is where eclipse gives an error. If i don't put " " around the 1 it works fine but now the Hackerrank API gives response code : 400 because testcase needs to be string. I can't figure out as to how to resolve this problem. Can someone please guide me.
Thanks in advance. This is the code:
package com.us.ABC;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
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("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://api.hackerrank.com/checker/submission.json";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "source=print 1&lang=5&testcases=["1"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
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();
//print result
System.out.println(response.toString());
}
}
You need to escape the double quotes in the string literal:
String urlParameters = "source=print 1&lang=5&testcases=[\"1\"]&api_key=hackerrank|282807-132|8d62bbbdf90d6a790747561f031a017b7f6cbbeb";

Java Server returned HTTP response code: 401

Hi I write java program to do a http post request by Http Basic Authentication
but it always shows error 401. My username and password is right can login the website. I don't know where wrong?
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.*;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.*;
#SuppressWarnings("unused")
public class hello {
/**
* #param args
*/
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
hello http = new hello();
//System.out.println("Testing 1 - Send Http GET request");
//http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
#SuppressWarnings("unused")
private void sendPost() throws Exception {
String url = "https://mds.datacite.org/doi";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
String userPassword= "username:password";
String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(userPassword)));
System.out.println(encoding);
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Authorization","Basic"+encoding);
String urlParameters = "doi=xxxxxx&url=http://xxxxx/dataset/1xxx099";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
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();
//print result
System.out.println(response.toString());
}
401 == Unauthorized, which means your username/password combo are incorrect
you need a space after "Basic" in the Authorization header

Categories

Resources