Gson ArrayList<different Objsct> - java

//output
String outStr = "";
ArrayList<DateItemVO> dateItem= dateItemDAO.findItemSeller(memberInteger);
ArrayList<Member> member= new ArrayList<Member>();
ArrayList<Pet> pet= new ArrayList<Pet>();
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
OrderVOAll orderVO = new OrderVOAll(dateItem,member,pet,restaurant);
Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
outStr = gson.toJson(orderVO);
rp.setContentType(text/html; charset=UTF-8);
PrintWriter out = rp.getWriter();
out.println(outStr);
//input
jsonIn = getRemoteImage(url, jsonObject.toString());
private String getRemoteImage(String url, String jsonOut) throws IOException {
StringBuilder jsonIn = new StringBuilder();
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoInput(true); // allow inputs
connection.setDoOutput(true); // allow outputs
connection.setUseCaches(false); // do not use a cached copy
connection.setRequestMethod("POST");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
bw.write(jsonOut);
Log.d(TAG, "jsonOut: " + jsonOut);
bw.close();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = br.readLine())!=null){
jsonIn.append(line);
}
Log.d(TAG, "jsonInqq: " + jsonIn);
} else {
Log.d(TAG, "response code: " + responseCode);
}
connection.disconnect();
return jsonIn.toString();
}
Gson gson= new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
return gson.fromJson(jsonIn,OrderVOAll.class);
the other side when i catch the json i got an errer.i can got the message from db ,but i dont know the reason why i got the msgm
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
thanks for help

Related

Why cannot post whole string of base64 using httpurlconnection?

I want to upload the image to the server.
I got the bitmap of the image and encoded it to base64.
I convert the base64 of the image to a string using the encodeToString method.
I post the string to PHP using httpurlconnection. Actually, I got the string from PHP which is not the whole string. I don`t get any error. Please give me feedback!
public String httpURLConnectionPost(final String urlString){
String result="";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.download);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.NO_CLOSE);
String body= "image="+encodedImage;
Log.d("serverPostData","body = " +body);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(body);
writer.close();
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while ((line = br.readLine()) != null) {
stringBuilder .append(line);
}
result = stringBuilder .toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
The php got the string and decode it.
<?php
include("mysqli_connect.php");
$image= $_POST['image'];
$a = uniqid() ;
$ImagePath = "good/$a.JPEG";
$ServerURL = "https://172.30.10.1/$ImagePath";
$InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;
if(mysqli_query($connect, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($image));
echo $image;
}else{
echo "failed";
}
mysqli_close();
?>
Try this to convert image to base64:
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
String encodedImageData = getEncoded64ImageStringFromBitmap(bitmap);
Now pass the data in API:
JsonObject data1 = new JsonObject();
data1.addProperty("imageData", "data:image/png;base64," + encodedImageData);
Now set ImageBitmap:
image.setImageBitmap(bitmap);
Here is the method:
private String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
And for HttpUrlConnection try this...
jsonObject = new JSONObject();
jsonObject.put("imageString", encodedImage);
String data = jsonObject.toString();
String yourURL = "yourphpfileurl";
URL url = new URL(yourURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setFixedLengthStreamingMode(data.getBytes().length);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
connection.connect();
InputStream in = new BufferedInputStream(connection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
in.close();
String result = sb.toString();
connection.disconnect();
Hope this one will work for you...
I solved my probelm that the base64 need to replace empty to "+".
<?php
include("mysqli_connect.php");
$image= $_POST['image'];
$change = str_replace(" ","+",$image);
$a = uniqid() ;
$ImagePath = "good/$a.JPEG";
$ServerURL = "https://172.30.10.1/$ImagePath";
$InsertSQL = "INSERT INTO Photoshop(photo) VALUES('$ServerURL')" ;
if(mysqli_query($connect, $InsertSQL)){
file_put_contents($ImagePath,base64_decode($change ));
echo $image;
}else{
echo "failed";
}
mysqli_close();
?>

Read any Language String from Google Translator in Android

I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -
public JSONObject getTranslatedText() {
StringBuilder sb = new StringBuilder();
String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
JSONObject response = null;
String json = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
String line1 = "{\n" + " 'q': '" + inputString + "',\n" + " 'target': '" + targetcodeString + "'\n" + "}";
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(line1);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = sb.toString();
response = new JSONObject(json);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return response;
}
The problem is it is not encoding properly and I am getting output like this -
Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E
Can I get some help please. Thanks in advance.
Try using Html.fromHtml(yourTranslatedStr).toString().
I tried that with Hindi and it worked.

How to send a json string as an input parameter to a POST request in android

and facing a problem in sending the JSON string to a POST request.
This is my URL: http://172.25.183.183:8080/JIRAservice/rest/runquery
Key : query
Value:
{ "jql": "project=<projectkey>",
"startAt": 0,
"maxResults": 100,
"fields": [
"summary",
"customfield_10006",
"status",
"description"
]
}
Where <projectkey> is the value stored in the shared preferences please help
this is my code
try{
TextView op=(TextView) findViewById(R.id.resp);
URL url=new URL("http://172.25.183.183:8080/JIRAservice/rest/runquery");
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setRequestMethod("POST");
String projectKey=Home.savedid;
JSONObject jsonParam = new JSONObject();
jsonParam.put("query", " "{ \"jql\": \"project=" + projectKey + "\", \"startAt\": 0, \"maxResults\": 100, \"fields\": [\"summary\",\"customfield_10006\", \"status\", \"description\"] }"");
how to send the parameters??
conn.setDoOutput(true);
DataOutputStream dbstrm=new DataOutputStream(conn.getOutputStream());
dbstrm.flush();
dbstrm.close();
int respnse=conn.getResponseCode();
String output="Request URl"+url;
output+=System.getProperty("line.separator");
output+=System.getProperty("line.separator")+"Response Code"+respnse;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line= "";
StringBuilder respop=new StringBuilder();
while((line=br.readLine())!=null){
respop.append(line);
}
br.close();
output +=System.getProperty("line.separator")+respop.toString();
op.setText(output);
}catch(MalformedURLException ae){
ae.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
try{
URL url=new URL("http://172.25.183.183:8080/JIRAservice/rest/runquery");
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String projectKey=Home.savedid;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("query"," { \"jql\": \"project=" + projectKey + "\", \"startAt\": 0, \"maxResults\": 100, \"fields\": [\"summary\",\"customfield_10006\", \"status\", \"description\"] }"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
int respnse=conn.getResponseCode();
String output="Request URl"+url;
output+=System.getProperty("line.separator");
output+=System.getProperty("line.separator")+"Response Code"+respnse;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line= "";
StringBuilder respop=new StringBuilder();
while((line=br.readLine())!=null){
respop.append(line);
}
br.close();
output +=System.getProperty("line.separator")+"IssueList from API"+respop.toString();
System.out.println("IssueList"+ output);
String respfield=resp(respop.toString());
System.out.println(" response"+ respfield);
}catch(MalformedURLException ae){
ae.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
getQuery() method
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}

in java how to copy data from file in the URL into excel worksheet

i am working on a system and need to fetch file from the URL using java URLConnection, Now all i need to copy that contents into excel file.
here is my code.
class getsize {
public static void main(String args[]) throws Exception {
HttpURLConnection conn = null;
try {
String plainCreds = "hmhinstall:hmh201208";
// String url = "http://content.link-systems.com/~hbern/content_update/";
byte[] plainCredsBytes = plainCreds.getBytes();
String base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = base64CredsBytes;
System.out.println(base64Creds);
int code = 0;
URL url = new URL("http://content.link-systems.com/~hbern/content_update/ ");
//Reading
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine); //Printing file data
}
in.close();
//Getting size
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + base64Creds);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setDoOutput(true);
System.out.println(conn.getResponseCode());
System.out.println(conn.getContentType());
conn.getInputStream();
System.out.println("Length : " + conn.getContentLength()); //Getting content length
} catch (Exception exception) {
} finally {
conn.disconnect(); //Disconnect
}
}
}
How can i copy contents of a file in to excel worksheet? So that i can generate records automatically.
thanks in advance

How to through a java application to transfer data to the servlet

I want to pass a java application sent a string that is a json,it isn't get this json in servlet, how do I do, who can help me?
This is my servlet code:
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
BufferedInputStream in = new BufferedInputStream(req.getInputStream());
byte[] data = null;
byte[] bts = new byte[1024];
int index;
while ((index = in.read(bts)) >= 0) {
if (data == null) {
data = new byte[index];
System.arraycopy(bts, 0, data, 0, index);
}
else {
byte[] tmp = data;
data = new byte[tmp.length + index];
System.arraycopy(tmp, 0, data, 0, tmp.length);
System.arraycopy(bts, 0, data, tmp.length, index);
}
}
String json = new String(data);
System.out.print(json);
}
and this is my java application:
String _url = "http://localhost:8080/jsf/test";
URL url = null;
HttpURLConnection urlconn = null;
String json = URLEncoder.encode(JSONObject.fromObject(req)
.toString(), "UTF-8");
url = new URL(_url);
urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestMethod("POST");
urlconn.setDoOutput(true);
urlconn.setDoInput(true);
OutputStream out = urlconn.getOutputStream();
out.write(json.getBytes("UTF-8"));
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlconn.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1) {
sb.append((char) ch);
}
System.out.println(sb);
rd.close();
You should write json data to outputStream as out.write(json.getBytes()); . See the complete code below:
String _url = "http://localhost:8080/jsf/test";
URL url = new URL(_url);
String json = "[{\"id\":\"DFAB8108D69642EBBD461160B4519B0F\",\"name\":\"name1\"},{\"id\":\"B048B2521A5619DCE0440003BA11CFDA\",\"name\":\"name2\"}]";
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestMethod("POST");
urlconn.setDoOutput(true);
OutputStream out = urlconn.getOutputStream();
out.write(json.getBytes());
out.flush();
out.close();
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlconn.getInputStream(), "UTF-8"));
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = rd.read()) > -1) {
sb.append((char) ch);
}
System.out.println(sb.toString());
rd.close();
Try something like this
String _url = "http://localhost:8080/jsf/test";
URL url = new URL(_url);
String json = "[{\"id\":\"DFAB8108D69642EBBD461160B4519B0F\",\"name\":\"name1\"},{\"id\":\"B048B2521A5619DCE0440003BA11CFDA\",\"name\":\"name2\"}]";
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn .setDoOutput(true);
urlconn .setRequestProperty("Content-Type", "application/json");
urlconn .setRequestProperty("Accept", "application/json");
urlconn .setRequestMethod("POST");
urlconn .connect();
OutputStream os = httpcon.getOutputStream();
os.write((json.getBytes("UTF-8"));
os.close();

Categories

Resources