Post request java http connection 403 forbidden error - java

I try to send a post request using a java program, I tested the post request URL in postman software, its working fine and post-operation are successful. But when I tried to replicate the same using java program with Http Url connection it pops out the 403 status as Forbidden.
Java code
public class Alexacreate {
public static void main(String Arg[]) throws MalformedURLException, IOException, JSONException {
JSONObject productjson = new JSONObject();
productjson.put("InternalID", "P987240");
String input = productjson.toString();
URL urlForUPdate = new URL("https://my348141.sapbydesign.com/sap/byd/odata/cust/v1/alexatest/MaterialCollection");
HttpURLConnection conn = (HttpURLConnection) urlForUPdate.openConnection();
conn.setRequestProperty("Authorization", "Basic RGV2VXNlcjAxOldlbGNvbWUwMQ==");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("x-csrf-token", "mQG3DNW_MMwaoIyvaqgepg==");
conn.setDoOutput(true);
conn.setDoInput(true);
System.out.println(input);
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
conn.connect();
System.out.println(conn.getResponseMessage());
if (conn.getResponseCode() == 201) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String outPut;
while ((outPut = bufferedReader.readLine()) != null) {
}
System.out.println("Created");
} else {
System.out.println("Not created");
}
}
}

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");

HttpUrlConnection 403-forbidden error Android

Below is my code snippet. 403 error coming. COuld anyone please give the solution to overcome this 403 error. This is the post JSON request.
#Override
protected String doInBackground(Void... voids) {
try {
trustAllHosts();
URL url = new URL(postUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userCredentials = username+":"+password;
String basicAuth = "Basic " + new String(android.util.Base64.encode(userCredentials.getBytes(), Base64.DEFAULT));
conn.setRequestProperty ("Authorization", basicAuth);
conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("X-CSRF-TOKEN",token);
conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
PostRootObject postRootObject = new PostRootObject();
Gson gson = new GsonBuilder().create();
String json = gson.toJson(postRootObject);
JSONObject jsonObject = new JSONObject(json);
Log.e("Json object",""+jsonObject);
DataOutputStream os = new
DataOutputStream(conn.getOutputStream());
// os.writeBytes(URLEncoder.encode(jsonObject.toString(), "UTF-8"));
os.writeBytes(jsonObject.toString());
os.flush();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG" , conn.getResponseMessage());
os.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
Maybe you are missing this line from your manifest file:
<uses-permission android:name="android.permission.INTERNET" />

Http Status 400 on android but 200 on desktop

I am trying to login to twitter using this code below:
//private final String USER_AGENT = "Mozilla/5.0";
private final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36";
public static void main(String[] args) throws Exception {
runThisClass("This is a samplest tweet234!");
}
public static void runThisClass(String tweet)throws Exception{
String url = "https://mobile.twitter.com/session/new";
String url2 = "https://mobile.twitter.com/session";
String url3 = "https://mobile.twitter.com";
String gmail = "https://mobile.twitter.com/compose/tweet";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// 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(url);
String postParams = http.getFormParams(page, "username", "password");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url2, postParams);
// 3. success then go to compose tweet page.
String result = http.GetPageContent(gmail);
//4.Construct another HTTP Post to tweet:
postParams=http.getTweetFormParams(result,tweet);
http.sendPostTweet(url3, postParams);
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "twitter.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("referer", "https://mobile.twitter.com/session");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
System.out.println("SendPostPost Params: "+postParams);
// 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);
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());
}
Now the problem I face is here(in method sendPost()):
int responseCode = conn.getResponseCode();
On a general PC, this works fine and I get response code as 200. But when run on android, this gives me 400. I wonder whats wrong here. Any help is very much appreciated and required.

Java HttpURLConnection post method Passing Parameters to cgi

I am a newbie in Java web programming. I am using HttpURLConnection to send data to a server via POST. I set the headers then get the output stream and write some bytes then close the output stream. As far as I know it is the correct way but the server send me an unknown exception.
Could you give me some hint why this exception happens
public static void main(String[] args) throws Exception {
String url = "http://www.nlm.nih.gov/cgi/mesh/2014/MB_cgi";
String cookie = retrieveCookies(url);
String urlParameters = "?term=Cancer&exact=Find Exact Term&field=all";
String page = postHttpPage(url , urlParameters, cookie);
System.out.println(page);
System.out.println();
}
public static String postHttpPage(String url, String urlParameters, String cookie) throws Exception {
System.out.println("\nSending 'POST' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
return postPage(conn, urlParameters, cookie);
}
private static String postPage(HttpURLConnection conn, String urlParameters, String cookie) throws Exception {
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Cookie", cookie);
//conn.setInstanceFollowRedirects(true);
// Send post request
//conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
//System.out.println("wr : " + wr.size());
wr.flush();
wr.close();
StringBuilder response = new StringBuilder();
int responseCode = conn.getResponseCode();
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static String retrieveCookies(String url) throws IOException{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
String cookies=conn.getHeaderField("Set-Cookie");
System.out.print("cookies: " + cookies);
conn.disconnect();
return cookies;
}
The problem is about the server. The server did not respond you if you send many requests and also sometimes it does not work might be due to the high amount of requests.

Java HttpURLConnection post method not working

I am using HttpURLConnection to send data to a server via POST. I set the headers then get the output stream and write some bytes then close the output stream.
I am trying to get the next page for schedule details from given url. But some how i am not getting the result. Please help anybody if you know any issue in this code.
I am getting first page with error instead of second page.
"The station combination you have chosen is invalid. Please call the LIRR Travel Information Center at (718) 217-5477 and ask for a representative for more information."
public static void main(String[] args) throws Exception {
String url = "http://lirr42.mta.info";
String cookie = retrieveCookies(url);
String urlParameters = "FromStation=56&ToStation=8&RequestDate=08/24/2013&RequestTime=01:00&RequestAMPM=PM&sortBy=1&schedules=schedules";
String page = postHttpPage(url + "/index.php", urlParameters, cookie);
System.out.println(page);
System.out.println();
}
public static String postHttpPage(String url, String urlParameters, String cookie) throws Exception {
System.out.println("\nSending 'POST' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
return postPage(conn, urlParameters, cookie);
}
private static String postPage(HttpURLConnection conn, String urlParameters, String cookie) throws Exception {
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Cookie", cookie);
//conn.setInstanceFollowRedirects(true);
// Send post request
//conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
//System.out.println("wr : " + wr.size());
wr.flush();
wr.close();
StringBuffer response = new StringBuffer();
int responseCode = conn.getResponseCode();
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static String retrieveCookies(String url) throws IOException{
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
String cookies=conn.getHeaderField("Set-Cookie");
System.out.print("cookies: " + cookies);
conn.disconnect();
return cookies;
}
You are missing the "?" Between index.php and the parameters.
You should make
String urlParameters = "FromStation=56&ToStation=8&RequestDate=08/24/2013&RequestTime=01:00&RequestAMPM=PM&sortBy=1&schedules=schedules";
into
String urlParameters = "?FromStation=56&ToStation=8&RequestDate=08/24/2013&RequestTime=01:00&RequestAMPM=PM&sortBy=1&schedules=schedules";
HttpURLConnection.getResponseCode();
this method may help you.
It forces the connection really establish the connection.
may be you want to use Apache HttpClient to make your life easier...

Categories