Error 405 - Method Not Found on Java HTTP function call - java

Need help on this piece of code. It's working fine on "POST" method. But when i changed it to "GET" for another API that accept GET method, it encounter 405 error.
P/S: I've tested the API using POSTMAN and managed to get proper respond.
try {
URL url = new URL(FullURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setReadTimeout(9000);
String input = "{\"accNo\": \"" + accNo + "\",\"token\": \"" + aToken +"\"}";
OutputStream os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
Integer HTTPResponse = conn.getResponseCode();
if(HTTPResponse != 200)
{
//System.out.println("HTTP Response Code: " + conn.getResponseCode());
}
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream())));
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read(cbuf)))
{
buf.append( cbuf, 0, num );
}
output = buf.toString();
conn.disconnect();
reader.close();
}

I've found the issue, was caused by the
setDoOutput(true)
It will implicitly set the request method to POST, since the targeted method is GET, the server will throw an 405 Method not allow error.

Related

java.io.EOFException: Response had end of stream after 0 bytes

I am trying to call a web service using a java code which is throwing java.io.EOFException: Response had end of stream after 0 bytes for the large chunk of data.
The same web service call works in Postman REST Client, but Java code throws an error and it is not able to fetch web service response.
Can someone please help me with this?
Below is the code snippet for reference:
String output;
URL url = new URL(wsUrl); //wsUrl is a web service URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
String authorization = "**************" + ":" + "*********";
String basicAuth = "Basic " + java.util
.Base64
.getEncoder()
.encodeToString(authorization.getBytes());
conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
System.out.println("Output from Server .... \n");
String jsonstring = new String();
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();

POST params empty, what am I doing wrong? HttpURLConnection / Android / Java

The code below shows a method, downloadUrl(), that takes a String, "myurl," its parameter. There are only two possible urls that I ever send to it, and the behavior of the method is different for each.
when myurl = URL1, it uses a GET request and everything works fine.
when myurl = URL2, however, it uses a POST request, and the response from the php page indicates that the post parameters sent with the request were empty. You can see the line where I set the POST params, so I don't understand why it's sending no params?!
Thanks for any help!
-Adam.
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
String response = "";
try {
URL urlObject = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) urlObject.openConnection();
// find out if there's a way to incorporate these timeouts into the progress bar
// and what they mean for shitty network situations
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setDoInput(true);
// INSERTED QUICK CHECK TO SEE WHICH URL WE ARE LOADING FROM
// it's important because one is GET, and one is POST
if (myurl.equals(url2)){
Log.i(TAG, "dlurl() in async recognizes we are doing pre-call");
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String postParams = "?phone=" + phone;
writer.write(postParams);
Log.i(TAG, "we're adding " + postParams + "to " + urlObject);
writer.flush();
writer.close();
os.close();
}
else {
conn.setRequestMethod("GET");
conn.connect();
}
// Starts the query
int responseCode = conn.getResponseCode();
Log.i(TAG, "from " + myurl + ", The response code from SERVER is: " + responseCode);
is = conn.getInputStream();
// Convert the InputStream into a string
// i guess we look up how to do this
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "from downloadUrl, php page response was not OK: " + responseCode;
}
// it's good to close these things?
is.close();
conn.disconnect();
Log.i(TAG, "response is " + response);
return response;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
try with following code block to send parameters of the POST request.
Map<String,String> params = new LinkedHashMap<>();
params.put("phone", "phone");
StringBuilder postPraamString = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postPraamString.length() != 0) postPraamString.append('&');
postPraamString.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postPraamString.append('=');
postPraamString.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
writer.write(postDataBytes);
So I figured out the root of the problem...
In the line:
String postParams = "?phone=" + phone;
The problem was that leading question mark. The question mark should only be used in GET requests.

Not able to execute URL with json value in JAVA API springs

I am tiring to execute some of my project URLs through JAVA APIs. But some of them contain JSON values. Its not accepting the JSON I am providing.
If I hit same URL through browser it executes. I am not getting what is going wrong. Are the " " specified not accepted ?
URL = http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
The Code is as follows
String requestString = "http://admin.biin.net:8289 /project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE"
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.connect();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer responseString = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
responseString.append(line);
}
Error :
java.io.IOException: Server returned HTTP response code: 505 for URL: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectJSON={"fieldIds":[{"id":1360,"value":"project SS33"},{"id":1362,"value":"12/03/2015"},{"id":1363,"value":"12/31/2015"}],"state":1}&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE
If I remove the JSON the URL executes.
Don't pass json in QueryString. Since you are using HTTP POST. You should send the sensitive data in the HTTP body. Like this
String str = "some string goes here";
byte[] outputInBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
For your current problem. Encode the json value before passing it in url.
Try this:
try {
String s = "http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON="
+ URLEncoder.encode("{\"fieldIds\":[{\"id\":1360,\"value\":\"project SS33\"},{\"id\":1362,\"value\":\"12/03/2015\"},{\"id\":1363,\"value\":\"12/31/2015\"}],\"state\":1}", "UTF-8")
+ "&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE";
System.out.println(s);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Result: http://admin.biin.net:8289/project.do?cmd=AddProject&mode=default&projectFieldValueJSON=%7B%22fieldIds%22%3A%5B%7B%22id%22%3A1360%2C%22value%22%3A%22project+SS33%22%7D%2C%7B%22id%22%3A1362%2C%22value%22%3A%2212%2F03%2F2015%22%7D%2C%7B%22id%22%3A1363%2C%22value%22%3A%2212%2F31%2F2015%22%7D%5D%2C%22state%22%3A1%7D&jsessionid=AE5B03C9791D1019DCD7BBF0E34CCFEE

Send formData in openConnection content withReader Grails

update : this is a duplicate,
i'm building a Proxy-custom-tag with grails taglib, per default it makes a get-request, now i'm facing the problem, that it should be able to handle Post-requests too,#
and i'm able to check the request-method and conditionally set the openConnection method to post if necessary, but i dont know how to append the post-params to the request.
here 's my code so far
def wordpressContent = { attrs, body ->
def url
def requestMethod = request.getMethod()
def queryString = request.getQueryString()?'&'+request.getQueryString():''
def content
println "method :"+requestMethod
println "params == "+params // <- inside here are the post-parameters
url = grailsApplication.config.wordpress.server.url+attrs.pageName+'?include=true'+queryString
try {
content = url.toURL().openConnection().with { conn ->
if(requestMethod == 'POST'){
println "Its a POST"
conn.setRequestMethod("POST")
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// HOW to append the params here ?
}
readTimeout = 6000
if( responseCode != 200 ) {
throw new Exception( 'Not Ok' )
}
conn.content.withReader { r ->
r.text
}
}
}
catch( e ) {
println "exception : "+e
content="<div class='float' style='margin-top:10px;width:850px;background-color:white;border-radius:5px;padding:50px;'>Hier wird gerade gebaut</div>"
}
out << content
}
im very stuck here right now, i found answers saying to use this syntax
Writer wr = new OutputStreamWriter(conn.outputStream)
wr.write(postParams)
wr.flush()
wr.close()
but i dont know how to include that to my existing code,
for any hints thanks in advance
update: my solution was to build up the post-parameter-querystring by iterating over the params object in this pattern "xyz=zyx&abc=cba" and write it to the outputStream like above
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection 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");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=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());
}
you are using grails so you can also use groovy HTTPBuilder like below
http://groovy.codehaus.org/modules/http-builder/doc/

Sending an HTTP POST request through the android emulator doesn't work

I'm running a tomcat servlet on my local machine and an Android emulator with an app that makes a post request to the servlet. The code for the POST is below (without exceptions and the like):
String strUrl = "http://10.0.2.2:8080/DeviceDiscoveryServer/server/devices/";
Device device = Device.getUniqueInstance();
urlParameters += URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode(device.getUser(), "UTF-8");
urlParameters += "&" + URLEncoder.encode("port", "UTF-8") + "=" + URLEncoder.encode(new Integer(Device.PORT).toString(), "UTF-8");
urlParameters += "&" + URLEncoder.encode("address", "UTF-8") + "=" + URLEncoder.encode(device.getAddress().getHostAddress(), "UTF-8");
URL url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(urlParameters);
wr.flush();
wr.close();
Whenever this code is executed, the servlet isn't called. However if I change the type of the request to 'GET' and don't write anything to the outputstream, the servlet gets called and everything works fine. Am I just not making the POST correctly or is there some other error?
try the following code, it may help u
try
{
String argUrl =
"";
String requestXml = "";
URL url = new URL( argUrl );
URLConnection con = url.openConnection();
System.out.println("STRING" + requestXml);
// specify that we will send output and accept input
con.setDoInput(true);
con.setDoOutput(true);
con.setConnectTimeout( 20000 ); // long timeout, but not infinite
con.setReadTimeout( 20000 );
con.setUseCaches (false);
con.setDefaultUseCaches (false);
// tell the web server what we are sending
con.setRequestProperty ( "Content-Type", "text/xml" );
OutputStreamWriter writer = new OutputStreamWriter( con.getOutputStream() );
writer.write( requestXml );
writer.flush();
writer.close();
// reading the response
InputStreamReader reader = new InputStreamReader( con.getInputStream() );
StringBuilder buf = new StringBuilder();
char[] cbuf = new char[ 2048 ];
int num;
while ( -1 != (num=reader.read( cbuf )))
{
buf.append( cbuf, 0, num );
}
String result = buf.toString();
System.err.println( "\nResponse from server after POST:\n" + result );
}
catch( Throwable t )
{
t.printStackTrace( System.out );
}
Out of curiosity I tried getting the response code for my request:
int responseCode = connection.getResponseCode();
System.out.println(responseCode);
This actually made the request go through and I got 200. I checked my Tomcat logs and the request finally got handled. I guess doing url.openConnection() and writing to the OutputStream isn't enough.

Categories

Resources