I'm using the code below to create a http request to my amazon AWS api gateway with an object (mp3Base64) as its content. However, it needs to have the authorization token attached. Can anyone explain how this is done and show an example? Any help is gratefully received. Thanks.
public String executePost(String targetURL, Mp3Base64 mp3Base64) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String mp3Base64Json = mapper.writeValueAsString(mp3Base64);
URL obj = new URL(targetURL);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
connection = (HttpURLConnection) obj.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(mp3Base64Json.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("base64=" + mp3Base64Json);
wr.flush();
wr.close();
//Get Response
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + targetURL);
System.out.println("Post parameters : base64 =" + mp3Base64Json);
System.out.println("Response Code : " + responseCode);
InputStream is = connection.getInputStream();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return response.toString();
}
I have this method to connect to my webservice (REST API)
public static void getHttpCon() throws Exception{
String tokenUrl = AppPropertiesService.getProperty( URL_TOKEN );
String username = AppPropertiesService.getProperty( USERNAME );
String password = AppPropertiesService.getProperty( PASSWORD );
String POST_PARAMS = "username="+username+"&password="+password+"&lang=fr&grant_type=password&client_id=apiclient";
URL obj = new URL(tokenUrl);
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");
}
}
I want to know how can i POSTa CSV File .
Should I do it directly in my method above ?
Do I have to create a new method by recovering the connection token from my method above?
My API ULR is POST /api/{id}/csv
I want to make java program to download a file from website, but i'm stuck in following situation. When I run the following code logging to page gets done successfully, but after it is done, when I send request for the next page, it shows response code 500.
public class Ss2mydb
{
private List<String> cookies;
private HttpURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
String indexPage = "http://10.100.100.142/index.asp";
String validatePage = "http://10.100.100.142/validate.asp";
String ccmenuPage = "http://10.100.100.142/callcentre/ccmenu.asp";
String reportPage = "http://10.100.100.142/topmgmt/reports/PROJECTVIJAY/get_download_cafs.asp";
String reportPageDownload = "http://10.100.100.142/topmgmt/reports/PROJECTVIJAY/get_download_cafs.asp?view=N";
Ss2mydb http = new Ss2mydb();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(indexPage);
String postParams = http.getFormParams(page, "username", "password");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(validatePage, postParams);
// System.exit(0);
// 3. success then go to gmail.
http.GetPageContent2(ccmenuPage);
String result = http.GetPageContent2(reportPage);
System.out.println(result);
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "10.100.100.142");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
System.out.println(" sendPost : "+cookie.split(";", 1)[0]);
conn.addRequestProperty("Cookie",cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "http://10.100.100.142/index.asp");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
// setCookies(conn.getHeaderFields().get("Set-Cookie"));
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());
}
private String GetPageContent2(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
System.out.println(" L : "+cookies);
if (cookies != null) {
for (String cookie : this.cookies) {
System.out.println(" GetPageContent : "+cookie.split(";", 1)[0]);
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
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();
// Get the response cookies
// System.out.println(" Get : "+conn.getHeaderFields().get("Set-Cookie"));
// setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
System.out.println(" L : "+cookies);
if (cookies != null) {
for (String cookie : this.cookies) {
System.out.println(" GetPageContent : "+cookie.split(";", 1)[0]);
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
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();
// Get the response cookies
System.out.println(" Get : "+conn.getHeaderFields().get("Set-Cookie"));
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("right");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("USERname"))
value = username;
else if (key.equals("password"))
value = password;
if(!key.equals(""))
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
500 means "Internal server error" (see HTTP codes and their meaning).
It does mean that the request you sent was understood and was valid HTTP, but either there is an internal, unrelated issue, or the request you send is missing some parameter or is sending some incorrect value, and that omission/mistake causes the server logic to crash (either because it fails a validation of the request content or in a deeper, uncontrolled way).
The only way to get more specific info would be seeing the server logs (and that if the developer was careful checking parameters and logging info).
Your best option is to analize the traffic between the web browser and the server using some tool like wireshark, and then analize the traffic between your client and the server and try to spot the differences.
Using http in java (eclipse) I have to POST a message using a given url with header of http authorization as 64 base encoded message and body has the information like grant type,password,username ,scope.There is a given content type,password,username.I want the client code and using it I should be able to get the message from the server and show that message as the output.
Here is a sample code
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setConnectTimeout(timeout);
con.setDoOutput(true);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream ());
wr.write(requestString);
wr.flush ();
wr.close ();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.t
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 HttpClassExample {
public static void main(String[] args) throws Exception {
HttpClassExample http = new HttpClassExample();
System.out.println("Testing Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String userName="world#gmail.com";
String password="world#123";
String url = "https://world.com:444/idsrv/issue/oauth2/token";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
String ClientId = "mmclient";
String ClientSecret = "norZGs5vkw+cmlKROazauMrZInW9jokxIRCmndMwc+o=";
String userpass = ClientId + ":" + ClientSecret;
String basicAuth = "Basic "+" "
+ javax.xml.bind.DatatypeConverter.printBase64Binary(userpass
.getBytes());
con.setRequestProperty("Authorization", basicAuth);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","Application/x-www-form-urlencoded");
String urlParameters = "grant_type=password&username="+userName+"&password="+password+"&scope=urn:meetingmanagerservice";
// 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());
}
}
I'm try to send Post request to Google elevation API and expecting response
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
private final String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true&key=<API KEY>";
URL obj = new URL(ELEVATION_API_URL);
java.net.HttpURLConnection con = (java.net.HttpURLConnection)obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
I'm sending request in this manner but I'm getting response code as 400.This is working when request sent from browser. What is wrong with this code.
To Allow me to get XML back I made the following changes to your project
StringBuilder response = new StringBuilder(); // placed on the top of your Class
**wr.writeBytes(urlParameters.toString());** // as you have it in your code
System.out.println("ResponseMessage : " + connection.getResponseMessage());
System.out.println("RequestMethod : " + connection.getRequestMethod());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
wr.flush();
wr.close();
// I changed the URL to :
private final String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/xml";
//**I get XML in the response**
return response.toString();
I think there is a problem with the url parameters.
Firstly because sending an empty elevation api request does return a code 400 (Invalid request. Missing the 'path' or 'locations' parameter.).
Secondly because this works (returning 200) :
public void test() throws Exception {
String ELEVATION_API_URL = "https://maps.googleapis.com/maps/api/elevation/json";
String USER_AGENT = "Mozilla/5.0";
String urlParameters = "locations=6.9366681,79.9393521&sensor=true";
URL obj = new URL(ELEVATION_API_URL + "?" + urlParameters);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "en-US");
//String urlParameters = request;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
}