Receiving a String from Java server to Client - java

I have a java client which sends JSON object to the server (REST service).
The code works perfect. My current server returns "RESPONSE", but I want to modify my code to return a string from server to client (something like "transfer was OK")- in addition to sending the object from client to server.
This is the code I have
Server:
#Path("/w")
public class JSONRESTService {
#POST
#Path("/JSONService")
#Consumes(MediaType.APPLICATION_JSON)
public Response JSONREST(InputStream incomingData) {
StringBuilder JSONBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(incomingData));
String line = null;
while ((line = in.readLine()) != null) {
JSONBuilder.append(line);
}
} catch (Exception e) {
System.out.println("Error Parsing: - ");
}
System.out.println("Data Received: " + JSONBuilder.toString());
// return HTTP response 200 in case of success
return Response.status(200).entity(JSONBuilder.toString()).build();
}
}
Client:
public class JSONRESTServiceClient {
public static void main(String[] args) {
String string = "";
try {
JSONObject jsonObject = new JSONObject("string");
// Step2: Now pass JSON File Data to REST Service
try {
URL url = new URL("http://localhost:8080/w/JSONService");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(jsonObject.toString());
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (in.readLine() != null) {
}
System.out.println("\nJSON REST Service Invoked Successfully..");
in.close();
} catch (Exception e) {
System.out.println("\nError while calling JSON REST Service");
System.out.println(e);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
So in order to return a string from the server to the client- I modified first the method in the server to return a string,
and I added this to my client :
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while (in.readLine() != null) {
sb.append(line);
break;
}
System.out.println("message from server: " + sb.toString());
in.close();
But my string is empty.
What am I doing wrong? How should I modify my server/client to receive a simple string back or even an object?
Thanks.

Your code (example):
package com.javacodegeeks.enterprise.rest.javaneturlclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class JavaNetURLRESTFulClient {
private static final String targetURL = "http://localhost:8080/w/JSONService";
public static void main(String[] args) {
try {
URL targetUrl = new URL(targetURL);
HttpURLConnection httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json");
String input = "{\"id\":1,\"firstName\":\"Liam\",\"age\":22,\"lastName\":\"Marco\"}";
OutputStream outputStream = httpConnection.getOutputStream();
outputStream.write(input.getBytes());
outputStream.flush();
if (httpConnection.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ httpConnection.getResponseCode());
}
BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
(httpConnection.getInputStream())));
String output;
System.out.println("Output from Server:\n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Java: Can't send HTTP Post Request in Catch

I need to post request to an API inside catch to store some logs.
But when I put it the request inside catch, it returned:
java.io.IOException: Server returned HTTP response code: 500 for URL
Code:
try {
...
} catch (Exception e) {
postRequest(...);
}
Code Post Request to API;
public static Object postRequest(...) throws IOException, ParseException {
URL url = new URL(API + "/" + pathName);
HttpURLConnection connection = getHttpURLConnection(url);
try (OutputStream os = connection.getOutputStream()) {
byte[] input = body.getBytes("utf-8");
os.write(input, 0, input.length);
}
try {
StringBuilder response = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), "utf-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(response.toString());
return obj;
} catch (IOException err) {
return null;
}
}

How can i connect to my MySQL database with an android app?

i am trying to do an android app to write some datas on MySQL database but it does not work i did a Java class for this and i think the problem comes from this. Here is my code :
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
BackgroundTask(Context ctx) {this.ctx = ctx;}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://localhost:8080/project/register.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String password = params[2];
String contact = params[3];
String country = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8") + "&" +
URLEncoder.encode("contact", "UTF-8") + "=" + URLEncoder.encode(contact, "UTF-8") + "&" +
URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Actually what i would like is to save name, password, contact and country in my database. The problem is this : "Registration success" is never returned it is always null. But i don't know why. When i try to compile it looks like there is no errors and i can see the app.
Thank you very much for your help !
Edit : This is the register.php :
<?php
require "init.php";
$u_name=$_POST["name"];
$u_password=$_POST["password"];
$u_contact=$_POST["contact"]";
$u_country=$_POST["country"];
$sql_query="insert into users values('$u_name', '$u_password', '$u_contact', '$u_country');";
//mysqli_query($connection, $sql_query));
if(mysqli_query($connection,$sql_query))
{
//echo "data inserted";
}
else{
//echo "error";
}
?>
And also the init.php :
<?php
$db_name = "project";
$mysql_user = "root";
$server_name = "localhost";
$connection = mysqli_connect($server_name, $mysql_user, "", $db_name);
if(!$connection){
echo "Connection not successful";
}
else{
echo "Connection successful";
}
?>
Thank you for your help !
My class PutUtility for getData(), PostData, DeleteData(). you just need to change package name
package fourever.amaze.mics;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private static String Content;
private StringBuffer sb1;
private StringBuffer response;
public void setParams(Map<String, String> params) {
this.params = params;
}
public void setParam(String key, String value) {
params.put(key, value);
}
public String getData(String Url) {
StringBuilder sb = new StringBuilder();
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) { }
}
return response.toString();
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return response.toString();
}
public String putData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
if (value.contains("+"))
value = value.replace("+", "%20");
//return sb.toString();
// Get the server response
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send PUT data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("PUT");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(false);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
;
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
// Send PUT data request
return Url;
}
public String deleteData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("DELETE");
httpConnection.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb1.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return Url;
}
}
And use this class like this
#Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ueid", params[0]);
put.setParam("firm_no", params[1]);
put.setParam("date_incorporation", params[2]);
put.setParam("business_name", params[3]);
put.setParam("block_no", params[4]);
try {
res = put.postData(
"Api URL here");
Log.v("res", res);
} catch (Exception objEx) {
objEx.printStackTrace();
}
return res;
}
#Override
protected void onPostExecute(String res) {
try {
} catch (Exception objEx) {
mProgressDialog.dismiss();
objEx.printStackTrace();
}
}
Please use this. Hope it helps you in future also.
Check this if this is the problem
$u_contact=$_POST["contact"]"
here is the problem i think so brother. replace with
$u_contact=$_POST["contact"];

Android HttpURLConnection wierd response

I am trying to get response data of a Http request. My code looks like this :
public class Networking {
// private variables
private URL mUrl;
private InputStream mInputStream;
public void Networking() {}
public InputStream setupConnection(String urlString) {
// public variables
int connectionTimeout = 10000; // milliseconds
int readTimeout = 15000; // milliseconds
try {
mUrl = new URL(urlString);
try {
// initialize connection
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
// setup connection
connection.setConnectTimeout(connectionTimeout);
connection.setReadTimeout(readTimeout);
connection.setRequestMethod("GET");
connection.setDoInput(true);
// start the query
try {
connection.connect();
int response = connection.getResponseCode();
if (response == 200) {
// OK
mInputStream = connection.getInputStream();
return mInputStream;
} else if (response == 401) {
// Unauthorized
Log.e("Networking.setupConn...", "unauthorized HttpURL connection");
} else {
// no response code
Log.e("Networking.setupConn...", "could not discern response code");
}
} catch (java.io.IOException e) {
Log.e("Networking.setupConn...", "error connecting");
}
} catch (java.io.IOException e) {
Log.e("Networking.setupConn...", "unable to open HTTP Connection");
}
} catch (java.net.MalformedURLException e) {
Log.e("Networking.setupConn..", "malformed url " + urlString);
}
// if could not get InputStream
return null;
}
public String getStringFromInputStream() {
BufferedReader br = null;
StringBuilder sb = new StringBuilder(5000);
String line;
try {
br = new BufferedReader(new InputStreamReader(mInputStream), 512);
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (java.io.IOException e) {
Log.e("BufferReader(new ..)", e.toString());
return null;
} finally {
if(br != null) {
try {
br.close();
}catch (java.io.IOException e) {
Log.e("br.close", e.toString());
}
}
}
return sb.toString();
}
}
The problem is that the getStringFromInputStream function always returns a string that is 4063 bytes long. ALWAYS! No matter what the url.
I checked, and the (line = br.readLine()) part of the code always returns a string of fixed length of 4063.
I don't understand this. Please help.
This my code which works for me:
public String getDataFromUrl(String httpUrlString)
URL url = new URL(httpUrlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
responseCode = urlConnection.getResponseCode();
if (responseCode != HttpStatus.SC_OK) {
return null;
} else { // success
BufferedReader in = null;
StringBuffer str = new StringBuffer();
try {
in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
str.append(inputLine);
}
} finally {
if (null != in) {
in.close();
}
urlConnection.disconnect();
}
return str.toString();
}
}
In my opinion, it could be helpful for you if you use a library for http request.
I could suggest retrofit or volley.
Besides that, you could just try other methods to get the String from the InputStream, there is an interesting reply for that here
The one that I've used is
BufferedInputStream bis = new BufferedInputStream(inputStream);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
buf.write((byte) result);
result = bis.read();
}
return buf.toString();

how to get other than english text as response using java

I am getting response from Wikipedia page and paste the response in html file. If I open the html file in browser I am not able to get the languages other than English as it is (I used UTF-8). I am attaching the picture of languages as in html.
I tried in couple of ways to get the response using java, and they are as follows,
Way 1,
URL url = new URL ("https://en.wikipedia.org/wiki/Sachin_Tendulkar");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
//System.out.println("Host --------"+url.getHost());
String encoding = new String (encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
connection.setDoInput (true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
String s = line.toString();
System.out.println(s);
}
I also tried the following code, but this also not showing the fonts as it is in
wiki,
URL url;
HttpURLConnection conn;
BufferedReader rd;
String line;
StringBuilder result = new StringBuilder();
try {
url = new URL("https://en.wikipedia.org/wiki/Sachin_Tendulkar");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
while ((line = rd.readLine()) != null) {
byte [] b = line.getBytes("UTF-8");
result.append(line);
System.out.println(result.append(line));
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
Couple of points:
Your code does not show how exactly you persist the response to the HTML file. Do you just redirect the standard output of the process to a file? Make sure you use UTF-8 even while writing to the output file.
Why do you System.out.println the whole StringBuffer instance in each iteration of the read loop?
Why do you call line.getBytes() and never use the output?
EDIT - Based on your comments, I really think the problem is with the clipboard manipulation. Try the code below, which stores the response directly to an output file.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HtmlDownloader {
private static final String USER_AGENT = "Mozilla/5.0";
private static final String ENCODING = "UTF-8";
public boolean download(String urlAddress, String outputFileName) {
HttpURLConnection con = null;
BufferedInputStream is = null;
BufferedOutputStream os = null;
try {
URL url = new URL(urlAddress);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Charset", ENCODING);
is = new BufferedInputStream(
con.getInputStream()
);
os = new BufferedOutputStream(
new FileOutputStream(outputFileName)
);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
public static void main(String[] args) {
HtmlDownloader d = new HtmlDownloader();
if (d.download("https://en.wikipedia.org/wiki/Sachin_Tendulkar", "c:\\wiki.html"))
System.out.println("SUCCESS");
else
System.out.println("FAIL");
}
}

How to Read from and Post to a Remote Server using Java

I am new to this type of problems. Here I want to make a request to a website API and get response in JSON format.
I then want to send this response directly to a a different remote URL.
See the below sample code
PostMethod post = new PostMethod("Your URL");
post.setRequestBody("your json data");
post.setRequestHeader("Content-type", "application/json;charset=utf-8");
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try
{
int result = httpclient.executeMethod(post);
s_log.info("Response status code: " + result);
s_log.info(post.getResponseBodyAsString());
}
catch (HttpException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
post.releaseConnection();
}
Reading from and writing to a remote URL can be done using the standard Java API and is detailed in the official Java tutorials:
https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
Reading:
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Writing
import java.io.*;
import java.net.*;
public class Reverse {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage: java Reverse "
+ "http://<location of your servlet/script>"
+ " string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[1], "UTF-8");
URL url = new URL(args[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
}
}

Categories

Resources