HttpUrlConnection.setConnectTimeout() not workig for java class - java

HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("POST");
con.setProperty("Content-Type", "application/json");
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
String urlparameters = "{...}";
con.setOutPut(true);
try(DataOutPutStream wr = new DataOutputStream(con.getOutputStream())){
wr.writebytes(urlparameters);
wr.flush();
}
catch(Exception e){
system.out.println(e.getmessage());
}
int responsocode = con.getResponsecode();
I am also using setconnecttimeout() out and setredtimeout() but still not getting 200 responsecode.
getting timeout exception message.
Is there any other possible reason?

Related

HTTP error 400 Bad Request when POSTing JSON data over HttpURLConnection

I am trying to connect to sharepoint to get the access token.I am using below code to call the api but getting 400 bad request.It's working with postman.
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// conn.setRequestProperty("Accept", "application/json;");
// conn.setRequestProperty("x-csrf-token", "fetch");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("User-Agent", "Java client");
JSONObject obj2 = new JSONObject();
obj2.put("grant_type", mygranttype);
obj2.put("client_id", clientid);
obj2.put("client_secret", secret);
obj2.put("resource", resource);
// System.out.println(conn.getHeaderFields());
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
out.write(obj2.toString());
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
I tried below options:
// conn.setRequestProperty("x-csrf-token", "fetch");
// conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
// conn.setRequestProperty("Accept-Charset", "UTF-8");
// conn.setRequestProperty("User-Agent", "Java client");

How to pass JSON body in HTTP Put in JAVA

Can someone explain me how to pass JSON parameter in request body.
I am using HttpURLConnection to create the connection, as below:
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url); //URL is hardcoded as of now
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000); //60 secs
con.setReadTimeout(60000); //60 secs
con.setRequestProperty("Accept-Encoding", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("cache-control", "no-cache");
con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");
JSONObject reqBody = new JSONObject();
reqBody.put("state", "4");
System.out.println(reqBody);
StringEntity params = new StringEntity(reqBody.toString());
if( reqBody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
How can I put set the req body here?
For specifying the body of your request:
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()

JAVA Send Post Request which contains XML String

Problem Description
I'm trying to write a code which is sending POST request to the server. As server yet doesn't exist I can't test this part of code. With the request I must send XML as a String which look likes the string below:
String XMLSRequest = "<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><AuthenticationHeader><Username>Victor</Username><Password>Apoyan</Password></AuthenticationHeader></soapenv:Body></soapenv:Envelope>"
Solution
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
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.format("request=%s", XMLSRequest);
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Question
Is this right way to send String (XML like string) as POST request to the server?
To POST a SOAP request, you would want to write the xml to the body of the request. You do not want to write it as a parameter of the request.
String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection con = (HttpsURLConnection) obj.openConnection();
// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream(); //get output Stream from con
os.write( XMLSRequest.getBytes("utf-8") );
os.close();
Specially this code works well for sending XML string in SOAP calling
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public static String sendXmlString(String xmlString){
String xmlResponceString = "";
try {
// Replace here with your target URL
URL url = new URL("http://www.dneonline.com/calculator.asmx");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set timeout as per needs
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
// Set DoOutput to true if you want to use URLConnection for output.
// Default is false
connection.setDoOutput(true);
connection.setUseCaches(true);
connection.setRequestMethod("POST");
// Set Headers
connection.setRequestProperty("Accept", "*/xml");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("User-Agent", "");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Write XML
OutputStream outputStream = connection.getOutputStream();
byte[] b = xmlString.getBytes("UTF-8");
outputStream.write(b);
outputStream.flush();
outputStream.close();
// Read XML
InputStream inputStream = connection.getInputStream();
byte[] res = new byte[2048];
int i = 0;
StringBuilder response = new StringBuilder();
while ((i = inputStream.read(res)) != -1) {
response.append(new String(res, 0, i));
}
inputStream.close();
xmlResponceString = new String(response.toString());
} catch (IOException e) {
e.printStackTrace();
}
return xmlResponceString;
}

Send request to Google Elevation API in Java

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();
}

Google ClientLogin authentication

I try make authentication using ClientLogin
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Email", "testonly%2Ein%2E2011%40gmail%2Ecom");
connection.setRequestProperty("Passwd", "mypass");
connection.setRequestProperty("accountType", "HOSTED");
connection.setRequestProperty("service", "apps");
connection.connect();
But I get Error=BadAuthentication. How I should correct my code?
You should set the proper application/x-www-form-urlencoded Content-type and use the OutputStream to write the POST body.
//Open the Connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// Form the POST parameters
StringBuilder content = new StringBuilder();
content.append("Email=").append(URLEncoder.encode(youremail, "UTF-8"));
content.append("&Passwd=").append(URLEncoder.encode(yourpassword, "UTF-8"));
content.append("&service=").append(URLEncoder.encode(yourapp, "UTF-8"));
OutputStream outputStream = urlConnection.getOutputStream();
outputStream.write(content.toString().getBytes("UTF-8"));
outputStream.close();
// Retrieve the output
int responseCode = urlConnection.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
See this example to handle the result to get the auth token.

Categories