Why HttpURLConnection.getInputStream stop working in Java - 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.

Related

Sending post using HttpURLConnection

I have a node.js which waits for post with 2 parameters (name and pass):
app.post('/login.html', function (req, res) {
log.info(req.body);
userName = req.body.name;
pass = req.body.pass;
...
}
I'm trying to send post with the 2 parameters via simple java application, but I can't see that it arrive to the node.js.
what am I missing ?
The java code:
public static void main(String[] args) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://83.63.118.111:31011/login.html");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setConnectTimeout(10000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String str = "name='root'&pass='123456'";
//System.out.print(str);
writer.write(str);
writer.flush();
Thread.sleep(100);
writer.close();
os.close();
}
Your code will close when start send data (send and stop)
You should wait it done.
Add code after writer.flush();
Example get response:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
or just get responseCode:
int responseCode = urlConnection.getResponseCode();
Your program wait send request success or fail.
I think you use Thread.sleep(100); to wait send request, but it stop your Thread (don't send data to server)
Your code have req.body, Express.js don't have it, need use middleware body-parser.

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

Java app store receipt validation

I am trying to validate an Apple App Store receipt from a Java service. I can not get anything back other than an error 21002, "Receipt Data Property Was Malformed". I have read of others with the same problem, but, have not see a solution. I thought this would be fairly straight forward, but, have not been able to get around the error. Here is my code:
EDIT By making the change marked // EDIT below, I now get an exception in the return from the verifyReceipt call, also makred //EDIT:
String hexDataReceiptData = "<30821e3b 06092a86 4886f70d 010702a0 .... >";
// EDIT
hexDataReceiptData = hexDataReceiptData.replace(">", "").replace("<", "");
final String base64EncodedReceiptData = Base64.encode(hexDataReceiptData.getBytes());
JSONObject jsonObject = new JSONObject();
try
{
jsonObject.put("receipt-data",base64EncodedReceiptData);
}
catch (JSONException e)
{
e.printStackTrace();
}
URL url = new URL("https://sandbox.itunes.apple.com/verifyReceipt");
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
//Send request
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(jsonObject.toString());
wr.flush();
//Get Response
BufferedReader rd =
new BufferedReader(new
InputStreamReader(connection.getInputStream()));
StringBuilder httpResponse = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
httpResponse.append(line);
httpResponse.append('\r');
}
wr.close();
rd.close();
// EDIT
// {"status":21002, "exception":"java.lang.IllegalArgumentException"}
As posted here: Java and AppStore receipt verification, do the base64 encoding in iOS and send to the server. But, why?

Encoding trouble: php api and java client program

I am sorry to post such a "noob question", but I can't solve my problem by myself.
I have a server-side script, written in php which returns different values, in this example all companynames which are stored in a MySQL DB.
-The column in the DB is encoded in UTF-8
-The php file is encoded in UTF-8
This is the server side script:
include_once('SQLHandler.php');
$SQLHandler = new SQLHandler();
if(isset($_POST['command'])){
$command = $_POST['command'];
switch($command){
case 'getCompanies':
echo utf8_encode('[["Test1"],["Test2"],["Test3"],["Test4"]]');
//echo json_encode( $SQLHandler -> getCompanies());
break;
}
}
it returns "[["Test1"],["Test2"],["Test3"],["Test4"]]".
However, when I want to analyze the returned String and parse it to an array (with json-simple library), the following occurs:
?[["Test1"],["Test2"],["Test3"],["Test4"]]
Unexpected token END OF FILE at position 0.
The Java Code is the following:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String line;
while ((line = rd.readLine()) != null){
System.out.println(line);
}
String jsonText = readAll(rd);
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(jsonText);
System.out.println(array);
System.out.println(array.toJSONString());
System.out.println(array.toString());
} catch(Exception e){
e.printStackTrace();
}
return null;
It is my first time working with java and json, so it is possible that I did a very easy to find error, but I would be very thankfull if you could point it out to me (and explain what I did wrong;))
Regards
Well, turns out it wasn't an encoding problem at all...
See my modified code:
ArrayList companies = new ArrayList<>();
try {
URL url = new URL("http://localhost/api.php");
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "command=getCompanies";
out.writeBytes(content);
out.flush();
out.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String wholeLine = "";
String line;
while ((line = rd.readLine()) != null) {
wholeLine = wholeLine + line;
}
is.close();
JSONArray array = (JSONArray) new JSONParser().parse(wholeLine);
for(Object obj : array.toArray()){
System.out.println(obj.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
I forgot to supply "line" to the parse function and instead parsed the wrong variable ^^
Regards

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 ...?

Categories

Resources