URLEncoder mangling my JSON - java

I am trying to make a REST call from an Android app, and I seem to be having trouble getting the proper data to the server. The node side of things is getting queries like the following:
{ '{"search_term":"eese"}': '' }
The sending code from the app is:
OutputStream out = urlConnection.getOutputStream();
String body = r.getJSONString();
String body_encoded = URLEncoder.encode(body, "UTF-8");
out.write(body_encoded.getBytes("UTF-8"));
out.close();
If I step through the above code, I see that body is
"{"search_term":"eese"}"
And advice?

It seems my issue arose from an incorrect Content-Type.
I added
urlConnection.setRequestProperty("Content-Type", "application/JSON");
and the server started getting the correctly formatted items.

Related

Whats the best way to extract response body from com.amazonaws.Response to JSON string

I am sending the following Sig4 request:
Response response = new AmazonHttpClient(new ClientConfiguration())
.requestExecutionBuilder()
.executionContext(new ExecutionContext(true))
.request(request)
.errorResponseHandler(new AWSErrorResponseHandler(false))
.execute(new AWSResponseHandler(false));
I then convert the response to httpResponse: (not sure if its needed)
com.amazonaws.http.HttpResponse httpResponse = response.getHttpResponse();
My issue is that I was unable to find a simple explanation on how to extract the actual JSON response
string out of my response.
EDIT: Note that when I follow the SDK doc and try to extract the content as an input stream:
IOUtils.toString(response.getHttpResponse().getContent());
I get the following exception:
java.io.IOException: Attempted read from closed stream.
at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:165)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:135)
at com.amazonaws.internal.SdkFilterInputStream.read(SdkFilterInputStream.java:90)
at com.amazonaws.event.ProgressInputStream.read(ProgressInputStream.java:180)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:106)
at com.amazonaws.util.IOUtils.toByteArray(IOUtils.java:44)
at com.amazonaws.util.IOUtils.toString(IOUtils.java:58)
Any assistant would be highly appreciated :)
For HTTP responses I used RestAssured. With this it should work like this:
Response response = new AmazonHttpClient().execute() // build and run your query
String json = response.getBody().prettyPrint();
If you want to use the information of the json directly afterwards within the code I can recommend creating a POJO and then doing the following:
AmazonResponseDto dto = response.as(AmazonResponseDto.class)
A quick look up of the com.amazonaws.http.HttpResponse docs showed me, that you can get an InputStream from it, but not directly a json.
I don't know the package of the Response you used in your first code block, that's why I recommended RestAssured.
I found the reason for my issue. As some have suggested, the response is an input stream, yet when I tried to extract it to starting I either got a closed connection exception or nothing. To fix this I had to change .execute(new AWSResponseHandler(true)); to true instead of false in order to keep the connection open. AWSResponseHandler implements HttpResponseHandler and sets the following:
public AWSResponseHandler(boolean connectionLeftOpen) {
this.needsConnectionLeftOpen = connectionLeftOpen;
}
I hope this helps anyone who gets into a similar situation.

How to send special character via HTTP post request made in Java

I need to send data to another system in a Java aplication via HTTP POST method. Using the Apache HttpClient library is not an option.
I create a URL, httpconection without problems. But when sending special character like Spanish Ñ, the system complains it is receiving
Ñ instead of Ñ.
I've read many post, but I don't understand some things:
When doing a POST connection, and writing to the connection object, is it mandatory to do the URLEncode.encode(data,encoding) to the data being sent?
When sending the data, in some examples I have seen they use the
conn.writeBytes(strData), and in other I have seen conn.write(strData.getBytes(encoding)). Which one is it better? Is it related of using the encode?
Update:
The current code:
URL url = new URL(URLstr);
conn1 = (HttpsURLConnection) url.openConnection();
conn1.setRequestMethod("POST");
conn1.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn1.getOutputStream());
wr.writeBytes(strToSend);//data sent
wr.flush();
wr.close();
(later I get the response)
strToSend has been previously URLENCODE.encode(,"UTF-8")
I still don't know if I must use urlencode in my code and/or setRequestProperty("Contentype","application/x-www-formurlencode");
Or if I must use .write(strToSend.getByte(??)
Any ideas are welcome. I am testing also the real server (I dont know very much about it)

What's the difference between using SoapUI and java code?

I'm using soap to request some information from server.
so, In order to test whether my soap way is the correct way or not, I tested soapUI Pro 4.6.3 program and java code.
when I use soapUI program , I got the response of my request from server. But, when I use java code I couldn't get response of my request from server..
I can see the error code 500. As I know, 500 Error code is Internal Error. so Isn't this problem of server?
I want to know what's the difference between them.
My java code is below.. and The XML code is the same what I use by SoapUI Program and what I use java code.
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("My URL");
int status = 0;
String result = "";
try {
method.setRequestBody(MySoapXML);
method.getParams().setParameter("http.socket.timeout", new Integer(5000));
method.getParams().setParameter("http.protocol.content-charset", "UTF-8");
method.getParams().setParameter("SOAPAction", "My Soap Action URL");
method.getParams().setParameter("Content-Type", MySoapXML.length());
status = client.executeMethod(method);
BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while ((readLine=br.readLine())!=null) {
System.out.println(readLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
and I already did URLConnection Class, and HttpClient Class.. but The result was the same..
If you know the way to solve this problem or have the same experience as me. please let me know how to solve this problem.. thank you for reading ^_^
Soap - UI will parse poorly defined webservices(for eg. Not Well Defined WSDL). From my experience working with SoapUI is not a proof that your webservice is well-defined.

Content Type header for POST request

I have in Java (similar in other languages, problem should be language independent) a POST request I am sending to the server. The POST request contains only some POST parameters no body.
I basically have this:
postData = URLEncoder.encode("user", "UTF-8") + "=" + URLEncoder.encode("jackychan", "UTF-8");
//HttpSessionToken.setRequestProperty("Content-Type", "application/xml");
OutputStream postContent = (OutputStream)HttpSessionToken.getOutputStream();
postContent.write(postData.getBytes("UTF-8"));
This works fine. The question is around the second line, a comment at the moment. Uncommenting this line ruins my code, okay my data is not XML so I can understand this. To some REST services you have to POST a whole XML document, but no POST parameters, something like this
postData = "<xml> whatever xml structure here </xml>"
HttpSessionToken.setRequestProperty("Content-Type", "application/xml");
OutputStream postContent = (OutputStream)HttpSessionToken.getOutputStream();
postContent.write(postData.getBytes("UTF-8"));
This works too. The difference is the postData is now an XML and the content type is set.
The question now is, what if a Service requires BOTH, POST parameters as in example 1 AND an xml body as in example 2. How would I do this? If that never happens, why doesn't it happen?
Thanks, A.
You could do that as multipart/form-data so you can have mixed content in a single POST body. It's similar to multipart-mime, and each part can have its own content-type. Here's a previous stackoverflow answer for multipart form-data in Java: How can I make a multipart/form-data POST request using Java?

File not found exception while reading connection.getInputStream()

I am sending a request on a server URL but I am getting File not found exception but when I browse this file through a web browser it seems fine.
URL url = new URL(serverUrl);
connection = getSecureConnection(url);
// Connect to server
connection.connect();
// Send parameters to server
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(parseParameters(CoreConstants.ACTION_PREFIX + actionName, parameters));
writer.flush();
// Read server's response
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
when I try to getInputStream then it throws error file not found.
It is an .aspx Controller page.
If the request works fine in a browser but not in code, and you've verified that the URL is the same, then the problem probably has something to do with how you are sending your parameters to the server. Specifically, this part:
writer.write(parseParameters(CoreConstants.ACTION_PREFIX + actionName, parameters));
Perhaps there is a bug in the parseParameters() function?
But more generally, I would recommend using something a bit higher-level than a raw URLConnection. HtmlUnit and HttpClient are both fine choices, particularly since it seems like your request is a fairly simple one. I've used both to perform similar client/server interaction in a number of apps. I suggest revising your code to use one of these libraries, and then see if it still produces the error.
Ok finally I have found that the problem was at IIS side it has been resolved in .Net 4.0. for previous version go to your web.config and specify validateRequest==false

Categories

Resources