Using HttpURLConnection, InputStreamReader, I get null response - java

I keep getting a "null" exception when I run this code. If I manually type the url string into my browser the php script posts "{query_result:SUCCESS}" indicating it worked, but when I try it via this code I just get the Exception e as "null". Can anyone help?
protected String signUp(String username) {
String link = "http://12.34.56.78/JSON_addUser.php";
String data = "";
BufferedReader bufferedReader;
String result = "";
String message;
try {
data += "?username=" + URLEncoder.encode(username, "UTF-8");
link += data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
message = "Exception trying: " + link + " Got: " + e.getMessage() + result;
return message;
}
}

Pretty often servers block requests like this because they are automated without a "User Agent" header. You might want to behave like a "real" browser.
Also i see a content encoding issue here. The constructor from InputStreamReader uses the default encoding and this might not be the encoding from the server--it might crash from converting the bytes into chars.

Related

Posting JSON to REST API from Java Servlet

I'm having issues trying to send over a JSON string to a REST API. Long story short, I'm taking user input in a form, sending it over to a java servlet to validate and work with it a bit, and then trying to send it to an endpoint.
I have the following method being called on in my doPost method in my servlet, I am using printwriter pw to be able to read back data being returned in my response in the browser console at this point.
String jsonData = //JSON STRING HERE\\
String username = //USERNAME\\
String password = //PASSWORD\\
String endpointURL = //ENDPOINT URL HERE\\
pw.println(sendJson(jsonData, username, password));
private String sendJSON(String jsonData, String usrname, String usrpass) {
try {
String auth = usrname + ":" + usrpass;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);
URL url = new URL(endpointURL);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
http.setConnectTimeout(5000);
http.setReadTimeout(5000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "application/json; utf-8");
http.setRequestProperty("Authorization", authHeaderValue);
http.setDoOutput(true);
//POST Json to URL using HttpURLConnection
//try(OutputStream os = http.getOutputStream()) {
OutputStream os = http.getOutputStream();
byte[] input = jsonData.getBytes("utf-8");
os.write(input, 0, input.length);
//}
/*String responseBody;
try(BufferedReader br = new BufferedReader(
new InputStreamReader(http.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//System.out.println(response.toString());
responseBody = response.toString();
return responseBody;
}
return responseBody;*/
BufferedReader in = new BufferedReader(
new InputStreamReader(http.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} catch (IOException e) {
return e.toString();
}
}
}
I was having issues with the try's so I rewrote it to try and just get functionality right away first. Right now I'm receiving "java.io.IOException: Server Returned HTTP response code: 500 for URL: //URL HERE\"
Would anybody have any tips to point me in the right direction? I feel like I'm just missing like a small piece of the puzzle at this point, and I'm having a hard time finding any tutorials showing what it is that I'm trying to do. Thank you so much to anyone for any tips/pointers!
Made sure I was able to authenticate and that wasn't the issue by just connecting and returning:
int statusCode = http.getResponseCode();
String statusCodeString = Integer.toString(statusCode);
return statusCodeString;
This worked fine, received 403 response when setting wrong password/username and 400 response when I change to correct.
I attempted using HttpClient as well instead, but was having issues trying to get that to work at all. I also had an error earlier with week trying to do this with a certificate error, but after reimporting the cert to my cacerts file this was resolved (unrelated to this issue I believe).

How to implement jdoodle API to compile and run java programs in Android Studio?

I am creating an android app too write and run java code in an android device using Android studio
we tried using the jdoodle API to compile and run the java code in the app. But whenever we tried to compile the code ye are getting error 400.
Please tell me how can I implement this API so that i can execute a java file.
we are using java language to write the program
Getting error code 400 while executing this:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
try {
String clientId = "af52e5b3d******c2d81bade***6c055"; //Replace with your client ID
String clientSecret = "e868414f******183267d398d578a448c6a1a70bf8be2896ebc******b013bc"; //Replace with your client Secret
String script = editText.getText().toString();
String language = "java";
String versionIndex = "0";
URL url = new URL("https://api.jdoodle.com/v1/execute");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
String input = "{\"clientId\": \"" + clientId + "\",\"clientSecret\":\"" + clientSecret + "\",\"script\":\"" + script +
"\",\"language\":\"" + language + "\",\"versionIndex\":\"" + versionIndex + "\"} ";
System.out.println(input);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Please check your inputs : HTTP error code : " + connection.getResponseCode());
}
BufferedReader bufferedReader;
bufferedReader = new BufferedReader(new InputStreamReader(
(connection.getInputStream())));
StringBuilder results = new StringBuilder();
String output1;
System.out.println("Output from JDoodle .... \n");
while ((output1 = bufferedReader.readLine()) != null) {
results.append(output1);
}
connection.disconnect();
output.setText(results);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
here we are pass
Error code 400 is a server side error. I means the server didn't understand your request. If I was to take a guess it would have to do with your input string. It does not appear to be written in the normal way variables are sent in post. That being said, a server can be written to accept the variables any way it wants to. But if it is the reason this is how the string should look.
name=value&name2=value2
You get the idea. Also JDoodle is a pay service. Most pay services will help you, they don't want to lose a client.

Java client POST to php script - empty $_POST

I have researched extensively and cannot find a solution. I have been using the solutions provided to other users and it does not seem to work for me.
My java code:
public class Post {
public static void main(String[] args) {
String name = "Bobby";
String address = "123 Main St., Queens, NY";
String phone = "4445556666";
String data = "";
try {
// POST as urlencoded is basically key-value pairs
// create key=value&key=value.... pairs
data += "name=" + URLEncoder.encode(name, "UTF-8");
data += "&address=" +
URLEncoder.encode(address, "UTF-8");
data += "&phone=" +
URLEncoder.encode(phone, "UTF-8");
// convert string to byte array, as it should be sent
byte[] dataBytes = data.toString().getBytes("UTF-8");
// open a connection to the site
URL url = new URL("http://xx.xx.xx.xxx/yyy.php");
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
// tell the server this is POST & the format of the data.
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestMethod("POST");
conn.setFixedLengthStreamingMode(dataBytes.length);
conn.getOutputStream().write(dataBytes);
conn.getInputStream();
// Print out the echo statements from the php script
BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while((line = in.readLine()) != null)
System.out.println(line);
in.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
and the php
<?php
echo $_POST["name"];
?>
The output I receive is an empty line. I tested to see if it was a php/server side issue by making an html form that sends data over to a similar script and prints the data on the screen and that worked. But, for the life of me, I cannot get this to work with a remote client.
I am using Ubuntu server and Apache.
Thank you in advance.
The problem is actually in what you read as output. You are doing two requests:
1)conn.getInputStream(); - sends POST request with desired body
2)BufferedReader in = new BufferedReader(
new InputStreamReader(url.openStream())); - sends empty GET request (!!)
Change it to:
// ...
conn.getOutputStream().write(dataBytes);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
and see result.

How to get response as XML from webService response?

I have to create a method for getting webService response as xml. I know how to create with Java class but problem is getting response as xml from webService.
These webServices are soap based.
Thanks in advance.
I have just solve my problem. HttpURLConnection helps me.
The following code block show how I make poster for getting xml response in java like Mozilla Poster.
public static void main(String[] args) {
try {
String uri = "http://test.com/IntegratedServices/IntegratedServices.asmx?op=GetUserInfo";
String postData = new XmlTest().xmlRequest("QWERTY10");
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // This is important. If you not set doOutput it is default value is false and throws java.net.ProtocolException: cannot write to a URLConnection exception
connection.setRequestMethod("POST"); // This is method type. If you are using GET method you can pass by url. If method post you must write
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); // it is important if you post utf-8 characters
DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); // This three lines is importy for POST method. I wrote preceding comment.
wr.write(postData.getBytes());
wr.close();
InputStream xml = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(xml));
String line = "";
String xmlResponse = "";
while ((line = reader.readLine()) != null) {
xmlResponse += line;
}
File file = new File("D://test.xml"); // If you want to write as file to local.
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(xmlResponse);
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String xmlRequest(String pin) {
return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
+ "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
+ " <soap:Body>\n"
+ " <GetUserInfo xmlns=\"http://tempuri.org/\">\n"
+ " <pin>" + pin + "</pin>\n"
+ " </GetUserInfo>\n"
+ " </soap:Body>\n"
+ "</soap:Envelope>";
}
I hope this helps who want to get xml as response. Also I wrote detailed comment to my code.
For soap type webservice :
Parsing SOAP Response in Java
For rest look at this link:
http://duckranger.com/2011/06/jaxb-without-a-schema/

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

Categories

Resources