In my application, I am trying get the response using POST request. The response server is sending me in Json format. But after adding the properties, it is returning me the response code as 411 (i.e issue with content length).
I have already added the content length. Then where is the issue i am not getting. Here is my code:
String url = "https://xxx:8243/people/v3";
STRURL = url + HttpComm.getConnectionString().trim();
StringBuffer postData = new StringBuffer();
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
postData.append("?username="+user);
postData.append("&password="+password);
String encodedData = postData.toString();
byte[] postDataByte = postData.toString().getBytes("UTF-8");
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type","application/json");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postData.toString().getBytes());
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
{
}
Updated Code :
HttpConnection httpConnection = null;
try {
httpConnection = (HttpConnection) Connector.open(STRURL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
};
try {
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
There are a few things that don't look quite right here. I would recommend trying this:
httpConnection.setRequestMethod("POST");
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
postData.append("username", user);
postData.append("password", password);
byte[] postDataByte = postData.getBytes();
httpConnection.setRequestProperty("Authorization", "bearer"+"ZWOu3HL4vwaOLrFAuEFqsxNQf6ka");
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestProperty("Content-Length", String.valueOf(postDataByte.length));
OutputStream out = httpConnection.openOutputStream();
DataOutputStream dos = new DataOutputStream(out);
out.write(postDataByte);
out.flush();
int statusCode = httpConnection.getResponseCode();
Logger.out("HttpComm", "status code::::::: "+statusCode);
if (statusCode != HttpConnection.HTTP_OK)
What I changed:
As #samlewis said, the code was creating a variable to hold the post data bytes, but then was not using it when it called out.write().
The code set the content type to JSON, but it was not sending JSON. The request was simply two parameters. The response may be JSON, but you don't specify that in the request's Content-Type parameter.
The username/password parameters were encoded just using strings. Normally, it's best to use the URLEncodedPostData class to hold your POST parameters.
If you are going to use strings, I think it was still incorrect to add a ? to the front of the username parameter. If you want to encode parameters in a GET URL, then you use https://xxx:8243/people/v3?username=user&password=password. But, this code was using POST, not GET.
There was also an unused encodedData variable.
Related
I am posting json data to the server but on getting the response it should be like this
{"id":65,"check":1,"date":"08-Jan-19"}
instead, I am getting this
{"id":"65check=1","check":null,"date":"08-Jan-19"}
This is the code on button click I send json form data to the server but in response, the id value gets attached to check value, how to get the proper response.
Attendance_TimeCheck = "1";
users_identify = "65";
try {
URL urlForPostRequest = new URL("http://xenzet.com/ds/getrec.php");
System.out.println("Instantiated new URL: " + urlForPostRequest);
final long id = Long.valueOf(users_identify);
HttpURLConnection conection = (HttpURLConnection) urlForPostRequest.openConnection();
conection.setDoOutput(true);
conection.setRequestMethod("POST");
conection.setRequestProperty("User-Agent", "Mozilla/5.0");
conection.getOutputStream().write(("id="+id).getBytes(StandardCharsets.UTF_8));
conection.getOutputStream().write(("check="+Attendance_TimeCheck).getBytes(StandardCharsets.UTF_8));
conection.connect();
BufferedInputStream bis = new BufferedInputStream(conection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int resultBuffer = bis.read();
while (resultBuffer != -1) {
bos.write((byte) resultBuffer);
resultBuffer = bis.read();
}
String result1 = bos.toString();
System.out.println(result1);
} catch (Exception ex) {
ex.printStackTrace();
}
I think the string is being read wrongly.
Check the payload you are passing to the POST request,
conection.getOutputStream().write(("id="+id).getBytes(StandardCharsets.UTF_8));
conection.getOutputStream().write(("check="+Attendance_TimeCheck).getBytes(StandardCharsets.UTF_8));
"id="+id followed by "check="+Attendance_TimeCheck will result to "id":"65check=1"
append the ampersand before the queryparam check to get the desired result,
conection.getOutputStream().write(("&check="+Attendance_TimeCheck).getBytes(StandardCharsets.UTF_8));
I'm trying to get my user information from stackoverflow api using a simple HTTP request with GET method in Java.
This code I had used before to get another HTTP data using GET method without problems:
URL obj;
StringBuffer response = new StringBuffer();
String url = "http://api.stackexchange.com/2.2/users?inname=HCarrasko&site=stackoverflow";
try {
obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
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;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But in this case I'm getting just stranger symbols when I print the response var, like this:
�mRM��0�+�N!���FZq�\�pD�z�:V���JX���M��̛yO^���뾽�g�5J&� �9�YW�%c`do���Y'��nKC38<A�&It�3��6a�,�,]���`/{�D����>6�Ɠ��{��7tF ��E��/����K���#_&�yI�a�v��uw}/�g�5����TkBTķ���U݊c���Q�y$���$�=ۈ��ñ���8f�<*�Amw�W�ـŻ��X$�>'*QN�?�<v�ݠ FH*��Ҏ5����ؔA�z��R��vK���"���#�1��ƭ5��0��R���z�ϗ/�������^?r��&�f��-�OO7���������Gy�B���Rxu�#:0�xͺ}�\�����
thanks in advance.
The content is likely GZIP encoded/compressed. The following is a general snippet that I use in all of my Java-based client applications that utilize HTTP, which is intended to deal with this exact problem:
// Read in the response
// Set up an initial input stream:
InputStream inputStream = fetchAddr.getInputStream(); // fetchAddr is the HttpURLConnection
// Check if inputStream is GZipped
if("gzip".equalsIgnoreCase(fetchAddr.getContentEncoding())){
// Format is GZIP
// Replace inputSteam with a GZIP wrapped stream
inputStream = new GZIPInputStream(inputStream);
}else if("deflate".equalsIgnoreCase(fetchAddr.getContentEncoding())){
inputStream = new InflaterInputStream(inputStream, new Inflater(true));
} // Else, we assume it to just be plain text
BufferedReader sr = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
StringBuilder response = new StringBuilder();
// ... and from here forward just read the response...
This relies on the following imports: java.util.zip.GZIPInputStream; java.util.zip.Inflater; and java.util.zip.InflaterInputStream.
I have a webservice whose content type is application/vnd.oracle.adf.resourceitem+json.
The HttpEntity of the reponse obtained by hitting this service is looks like this
ResponseEntityProxy{[Content-Type: application/vnd.oracle.adf.resourceitem+json,Content-Length: 3,Chunked: false]}
When I try to convert this HttpEntity into String it gives me a blank String {}.
Below are the ways I tried to convert the HttpEntity to String
1.
String strResponse = EntityUtils.toString(response.getEntity());
2.
String strResponse = "";
String inputLine;
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
try {
while ((inputLine = br.readLine()) != null) {
System.out.println(inputLine);
strResponse += inputLine;
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
3.
response.getEntity().writeTo(new FileOutputStream(new File("C:\\Users\\harshita.sethi\\Documents\\Chabot\\post.txt")));
All returns String -> {}.
Can anyone tell me what am I doing wrong?
Is this because of the content type?
The above code is still giving the same response with empty JSON object. So I modified and wrote the below code. This one seems to run perfectly fine.
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization", getAuthToken());
con.addRequestProperty("Content-Type", "application/vnd.oracle.adf.resourceitem+json;charset=utf-8");
String input = String.format("{\"%s\":\"%s\",\"%s\":\"%s\"}", field, value, field2, value2);
System.out.println(input);
OutputStream outputStream = con.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
con.connect();
System.out.println(con.getResponseCode());
// Uncompressing gzip content encoding
GZIPInputStream gzip = new GZIPInputStream(con.getInputStream());
StringBuffer szBuffer = new StringBuffer();
byte tByte[] = new byte[1024];
while (true) {
int iLength = gzip.read(tByte, 0, 1024);
if (iLength < 0) {
break;
}
szBuffer.append(new String(tByte, 0, iLength));
}
con.disconnect();
returnString = szBuffer.toString();
Authentication method
private String getAuthToken() {
String name = user;
String pwd = this.password;
String authString = name + ":" + pwd;
byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes());
System.out.println(new String(authEncBytes));
return "Basic " + new String(authEncBytes);
}
In case anybody faces the same issue. Let me share the challenged I faced and how I rectified those.
The above code works for all content-types/methods. Can be used for any type (GET, POST, PUT,DELETE).
For my requirement I had a POST webservice with
Content-Encoding →gzip
Content-Type →application/vnd.oracle.adf.resourceitem+json
Challenges : I was able to get the correct response code but I was getting junk characters as my response string.
Solution : This was because the output was compressed in gzip format which needed to be uncompressed.
The code of uncompressing the gzip content encoding is also mentioned above.
Hope it helps future users.
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.
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