Character encoding in web applicaion running on Websphere Application Server 8.5 - java

I have a problem with Cyrillic symbols represention (they looks as '0B0;lO') in IBM WebSphere Application I created.
So I use WebSphere 8.5 (Unix Red Hat) and application is a java-servlet which listens to HTTP POST Requests.
JVM properties on WebSphere are:
Default Charset=UTF-8
Default Charset= in use=UTF-8
file.encoding=UTF-8
I have checked file encoding.properties and set encoding to UTF8. Requests to my application I send in UTF8 by following code:
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
connection.setRequestProperty("Content-Length", Integer.toString(resultXML.getBytes().length));
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
// BufferedWriter br = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
BufferedWriter br1 = new BufferedWriter(new OutputStreamWriter(wr, Charset.forName("UTF-8")));
br1.write(resultXML);
br1.close();
wr.flush ();
wr.close ();
//Get Response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
rd.close();
In application HTTP Request Handler first of all I set encoding by:
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
But all Cyrillic symbols in request and response looks uncorrectly and when appplication put them to Oracle DB or simply to response these symbols have wrong view.
Help with problem, please!

This issue is resolved.
Request Cyrillic symbols was processed correctly, problem was with response. Following code helped.
PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
for (int i = 0; i < result.length(); i++)
{
out.print(result.charAt(i));
}
out.flush();

Related

Why HttpURLConnection.getInputStream stop working in Java

My program below stopped at the line:
InputStream is = conn.getInputStream();
Neither error message popped up nor any output displayed on the console.
I am running Eclipse Oxygen 4.7.0 on Red Hat Enterprise Linux Server release 7.4.
public static void solveInstance(String instanceName){
// solve a problem instance
try{
String query_url = "http://localhost:8807/scheduler";
// read Request to a JSON Object
JSONParser parser = new JSONParser();
JSONObject request = (JSONObject) parser.parse(new FileReader(instanceName));
// open connection
URL url = new URL(query_url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// POST Request
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
osw.write(request.toString());
osw.close();
// Get Response
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader in = new BufferedReader(isr);
String inputLine;
StringBuffer response = new StringBuffer();
while(( inputLine = in.readLine()) != null )
{
response.append(inputLine);
}
in.close();
// Write response to a file
JSONObject jsonObj = (JSONObject) parser.parse(response.toString());
String responseFile = /path_to_result/result.json;
FileWriter fileWriter = new FileWriter(responseFile);
fileWriter.write(jsonObj.toString());
fileWriter.flush();
fileWriter.close();
System.out.println("Solved" + instanceName);
}
catch(Exception e) {
System.out.println(e);
}
}
I noticed that the similar question is asked InputStream is = httpURLConnection.getInputStream(); stop working
but it was for Android and no solution was given there.
Does anyone have some idea on that? Do not hesitate to point out anything else wrong in my code.
Thanks a lot!
Your server isn't responding.
It would be wise to set a read timeout, with conn.setReadTimeout(5000) (say). Adjust the timeout as necessary.
Check response code
int response = connection.getResponseCode();
If you get 301 it means that your resource is redirected. Try to change URI from http to https.
It helped in my case.

Java - Reading POST from HttpURLConnection throwing response code 400

I am opening an HttpURLConnection and with POST method, I am sending a JSON request that I build form another class. The JSON is structured correctly since I have validated it on debugging. The exception is thrown when trying to read the output response given from the server. This is the Error given
java.io.IOException: Server returned HTTP response code: 400 for URL:
However when I manually try to enter the Url from a web browser with a POST method chrome extension. I can view the response and everything works. So I am sure it has something to do with the following code where I make the connection and read/write.
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//add request header
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
//mapping objects to json
BatchRequest requestParameters = new BatchRequest(o,d);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(requestParameters);
connection.setDoOutput(true);
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.writeBytes(json);
os.flush();
os.close();
// this is where the program throws the exception
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Both the URL and the JSON request are correct since They work when I try a manual conenction over a browser.
A DataOutputStream is not needed. Just:
OutputStream os = con.getOutputStream();

java.lang.IllegalStateException: Cannot use BufferedReader while ServletInputStream is in use

Can Java experts help me on this issue, I'm geting the error below
java.lang.IllegalStateException: Cannot use BufferedReader while ServletInputStream is in use
I'm calling a REST service url to post some data using a server side java code, not through a browser.
try{
String urlLocation = "http://myserver/james/dev/hello.nsf/services.xsp/test";
URL url = new URL(urlLocation);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty( "Content-type", "application/x-www-form-urlencoded" );
//connection.setRequestProperty( "Content-length", Integer.toString(content.length()));
DataOutputStream out = new DataOutputStream (connection.getOutputStream ());
out.writeBytes (getXML());
out.flush ();
out.close ();
connection.disconnect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while( (line = in.readLine()) !=null) {
System.out.println(line);
}
in.close();
}
catch(Exception e){
System.out.println("Error from 2nd try statement");
e.printStackTrace();
e.toString();
}
Any help will be greatly appreciated...
It seems to be this line
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
I noticed the BufferedReader is not being instantiated, you are reusing an instance variable in.
I copied your code and just changed it to this, and I can make multiple requests without any problem.
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));

Intercepting json in https(not http) with a python cgi script

I am sending json string in an https post request to an apache servert(request sends json data to a cgi-bin script that actually is a python script). Am using a standard cgi call -
f=open("./testfile", "w+")
f.write("usageData json = \n")
<b>form = cgi.FieldStorage()
formList = ['Data']
str = form['Data'].value
str = json.dumps(backupstr)
</b>
print backupstr
to read the json string in the url. Problem is that the script is not reading the json in the url even though the script is getting fired (the basic print statements are executing ...). This is how am sending data from the post side :
HttpsURLConnection connection = null;
try{
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/json");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(jsonstring.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
//wr.writeBytes(jsonstring);
wr.writeUTF(URLEncoder.encode(jsonstring, "UTF-8"));
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
//response = httpClient.execute(request);
}
catch (Exception e)
{
System.out.println("Exception " + e.getMessage());
throw e;
}
I suspect am missing one or more of the connection.setRequestProperty() settings on the sending end that's why it's firing the script but not reading the json string in the url ...what am I doing wrong ...?

Posting to a user's wall using the POST request and graph API

I am new to facebook app development and i have been trying to post a simple message on the wall of the user.i have managed to get the access token .Here is the code for the POST request.I am using java servlets
String data = URLEncoder.encode("access_token", "UTF-8") + "=" + URLEncoder.encode(accessToken, "UTF-8");
data += "&" + URLEncoder.encode("message", "UTF-8") + "=" + URLEncoder.encode("finally", "UTF-8");
out.println("data is\n"+data);
// Send data
String u="https://graph.facebook.com/me/feed";
URL urls = new URL(u);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
Well this code is not working and i can not post on the wall.Any suggestion as to where i might be wrong?
I'm pretty sure that it's because you don't specify the application/x-www-form-urlencoded content type, try this:
URLConnection connection = new URL("https://graph.facebook.com/me/feed").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(data);
out.flush();
out.close()
Edit
Ok, so there are two more things that might cause this problem:
You also need to specify the content length.
You might need to read the response to make it count..
This code was tested and it works:
StringBuffer buffer = new StringBuffer();
buffer.append("access_token").append('=').append(ACCESS_TOKEN);
buffer.append('&').append("message=").append('=').append("YO!");
String content = buffer.toString();
URLConnection connection = new URL("https://graph.facebook.com/me/feed").openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", Integer.toString(content.length()));
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(content);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
in.close();

Categories

Resources