Receiving response from CURL in JAVA - java

I am using a public API provided by Sentiment-140 for finding whether a small text is positive, negative or neutral. Though I can successfully use their simple HTTP-JSON service, I'm failing with CURL. Here's my code :
public static void makeCURL(String jsonData) throws MalformedURLException, ProtocolException, IOException {
byte[] queryData = jsonData.getBytes("UTF-8");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8080));
HttpURLConnection con = (HttpURLConnection) new URL("http://www.sentiment140.com/api/bulkClassifyJson").openConnection(proxy);
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
InputStream instr = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(instr));
os.write(queryData);
os.close();
String lin;
while((lin = br.readLine())!=null){
System.out.println("[Debug]"+lin); // I expect some response here But it's not showing anything
}
}
What am I doing wrong?

You should send all your request data before getting input stream of connection.
byte[] queryData = jsonData.getBytes("UTF-8");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.1.1.1", 8080));
HttpURLConnection con = (HttpURLConnection) new URL("http://www.sentiment140.com/api/bulkClassifyJson").openConnection(proxy);
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(queryData);
os.close();
InputStream instr = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(instr));
String lin;
while((lin = br.readLine())!=null){
System.out.println("[Debug]"+lin);
}

Related

Java - How to open one HttpURLConnection for both GET and POST

The request is to GET content from url and handle the content(different every time) properly, then POST the answer back to the same url. I encounter "Can't reset method: already connected" when I try to setRequestMethod("POST") after GET method executed. My code as below
public class MyClass {
/**
* #param args
*/
public MyClass() {};
public void process() {
String url = "http://www.somesite.com/";
String strPage = null;
int n = 0;
try{
URL urlObj = new URL(url);
HttpURLConnection urlConnection =
(HttpURLConnection)urlObj.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String strWhole = null;
while(null != (strPage = reader.readLine())){
strWhole += strPage;
}
//handle content here and calculate result
... ...
//send result below
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String urlParameters = "aa=bb&cc=dd&ee=ff";
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream in1 = urlConnection.getInputStream();
BufferedReader reader1 = new BufferedReader(new InputStreamReader(in));
while(null != (strPage = reader1.readLine())){
System.out.println(strPage);
}
reader1.close();
}
catch(Exception e){
String exception = e.getMessage();
System.out.println(exception);
if (reader != null) {
reader.close();
}
if (reader1 != null) {
reader1.close();
}
}
return;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyClass dp = new MyClass();
dp.process();
}
}
It is impossible to reuse HttpURLConnection instance. But documentation says that under the hood, Java reuses connections for you:
The JDK supports both HTTP/1.1 and HTTP/1.0 persistent connections.
When the application finishes reading the response body or when the application calls close() on the InputStream returned by URLConnection.getInputStream(), the JDK's HTTP protocol handler will try to clean up the connection and if successful, put the connection into a connection cache for reuse by future HTTP requests.
The support for HTTP keep-Alive is done transparently.
Therefore, there is no need to reuse connections manually.
You must set all parameters first. Here's a code i use in my application:
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("app_token", "my token"); // optional header you can set with your own data
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
InputStream is = connection.getInputStream();
byte[] b = readWithoutSize(is);
is.close();
The readWithoutSize is:
public static byte[] readWithoutSize(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
byte[] buf = new byte[512];
int leu;
while ((leu = is.read(buf)) != -1)
baos.write(buf,0,leu);
return baos.toByteArray();
}

Java httpserver crashes upon receiving POST requests

I am trying to write a simple HTTP server in Java that can handle POST requests. While my server successfully receives the GET, it crashes on the POST.
Here is the server
public class RequestHandler {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/requests", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "hello world";
t.sendResponseHeaders(200, response.length());
System.out.println(response);
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
And here is the Java code I use to send the POST
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://localhost:8080/requests";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
Each time the POST request crashes on this line
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
but when I change the URL to the one provided in the example where I found this it works.
Instead of
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
Use
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
You are connecting to a URL which is not HTTPS. When you call obj.openConnection(), it decides whether the connection is HTTP or HTTPS, and returns the appropriate object. When it's http, it won't return an HttpsURLConnection, so you cannot convert to it.
However, since HttpsURLconnection extends HttpURLConnection, using HttpURLConnection will work for both http and https URLs. The methods that you are calling in your code all exist int the HttpURLConnection class.

How to Decode a xml Sent over Url in java

I am firing an online xml in java to the method below:
public String WriteToServer(String xml) {
StringBuilder answer = new StringBuilder();
try {
String myurl="example.com";
URL url = new URL(myurl);
URLConnection conn = url.openConnection(Proxy.NO_PROXY);
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(xml);
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
} catch (Exception e) {
System.out.println(e);
}
return answer.toString();
}
My Problem is that the server receives an encoded xml so it can not understand and returns a 500 response to the client. How can I decode a xml to a plain text that the server can read?
Try below code just before creating OutputStreamWriter instance
String myurl="example.com";
URL url = new URL(myurl);
URLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Language", "en-US");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);

HttpURLConnection Error - java.io.IOException: Server returned HTTP response code: 400 for URL

I am trying to connect to a URL from a desktop app, and I get the error indicated in the Title of my question
Url:https://capi-eval.signnow.com/api/user
The Code fragment.
public void getUrl(String urlString) throws Exception
{
String postData=String.format("{{\"first_name\":\"%s\",\"last_name\":\"%s\",\"email\":\"%s\",\"password\":\"%s\"}}", "FIRST", "LAST","test#test.com","USER_1_PASSWORD");
URL url = new URL (urlString);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Length",""+postData.length());
connection.setRequestProperty ("Authorization", "Basic MGZjY2RiYzczNTgxY2EwZjliZjhjMzc5ZTZhOTY4MTM6MzcxOWExMjRiY2ZjMDNjNTM0ZDRmNWMwNWI1YTE5NmI=");
connection.setRequestMethod("POST");
connection.connect();
byte[] outputBytes =postData.getBytes("UTF-8");
OutputStream os = connection.getOutputStream();
os.write(outputBytes);
os.close();
InputStream is;
if (connection.getResponseCode() >= 400) {
is = connection.getErrorStream();
} else {
is = connection.getInputStream();
}
BufferedReader in =
new BufferedReader (new InputStreamReader (is));
String line;
while ((line = in.readLine()) != null) {
System.out.println (line);
}
}
public static void main(String[] arg) throws Exception
{
System.setProperty("jsse.enableSNIExtension", "false");
Test s = new Test();
s.getUrl("https://capi-eval.signnow.com/api/user");
}
When i dig in the response and print error Stream My output is ::
{"errors":[{"code":65536,"message":"Invalid payload"}]}
any help appreciated
thanks
Maybe something wrong caused by unecoding. Just have a try by using Base64.encode.

Call POST data from one servlet to another server

I am submitting JSON data from my GWT-Client and Passing it to my GWT-Server. And i want to re-submit data to another server and want response from another server to GWT-Client.
I just don't know how can i do this. I tried below code but not working.
My Code is :
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST");
StringBuffer jb = new StringBuffer();
URL oracle = new URL("http://www.google.com");
HttpURLConnection connection = null;
connection = (HttpURLConnection) oracle.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
request.getInputStream();
OutputStream wr = connection.getOutputStream();
InputStream in = request.getInputStream();
byte[] buffer = new byte[512];
int read = in.read(buffer, 0, buffer.length);
while (read >= 0) {
wr.write(buffer, 0, read);
read = in.read(buffer, 0, buffer.length);
}
wr.flush();
wr.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in1.readLine()) != null) {
jb.append(inputLine);
}
response.setContentType("text/html");
// Get the printwriter object from response to write the required json
// object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following,
// it will return your json object
out.print(jb.toString());
out.flush();
in1.close();
}
Please help me.
You'll have to send the request to the other server before reading the response
URL oracle = new URL("http://www.anotherserver.com/");
HttpURLConnection connection = null;
connection = (HttpURLConnection) oracle.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream wr = connection.getOutputStream ();
InputStream in = request.getInputStream();
byte[] buffer = new byte[512];
int read = in.read(buffer,0, buffer.length);
while (read >= 0) {
wr.write(buffer,0, read);
read = in.read(buffer,0,buffer.length);
}
wr.flush ();
wr.close ();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
jb.append(inputLine);
}
see also Using java.net.URLConnection to fire and handle HTTP requests
In addition, you can use Apache httpclient, it's very simple to implement your requirement, such as :
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.anotherserver.com/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("key",
"value"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Categories

Resources