Android - get request received EOFException - java

Code:
String recipeName = this.recipe.getName().replace(" ", "%20");;
String recipeIngredients = this.recipe.getIngredients().replace(" ", "%20");;
String recipeInstructions = this.recipe.getInstructions().replace(" ", "%20");;
String recipeUserName = this.recipe.getUserName().replace(" ", "%20");;
int recipeRate = this.recipe.getRate();
int recipeAmountOfRate = this.recipe.getAmountOfRates();
String link = "http://***My_Site***/createRecipe.php?recipeName="+recipeName+"&recipeIngredients="+recipeIngredients
+"&recipeInstructions="+recipeInstructions+"&recipeUserName="+recipeUserName+"&recipeRate="+recipeRate+
"&recipeAmountOfRate="+recipeAmountOfRate;
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setChunkedStreamingMode(0);
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = in.read()) != -1) {
sb.append((char) ch);
}
Log.e("Error", sb.toString());
} catch(Exception e) {
Log.e("Error", e.toString());
} finally {
urlConnection.disconnect();
}
}
But i get the error:
E/Error: java.io.EOFException
Why is that?
in previous requests the request went good.
Doed the URL request too long?

Related

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.

multiple upload images file using httpurlconnection

I have many images in a folder, and I want to upload this files, in that folder, to a php server, in java using httpurlconnection.
Until now, I made it but just with one photo, like the code I show you down.
public class SendImage {
private final String CrLf = "\r\n";
public static void main(String[] args) {
SendImage image = new SendImage();
image.httpConn();
}
private void httpConn(){
URLConnection lig = null;
OutputStream os = null;
InputStream is = null;
try{
String urlParameters = "subPasta=sandro&nomepc=Sandro-PC&printPasta=Printscreens";;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
URL url = new URL("http://192.168.0.105/dashboard3/uploadImg.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
System.out.println("url: "+ url);
lig = url.openConnection();
lig.setDoOutput(true);
FileInputStream imgIs = new FileInputStream(new File("C:\\Users\\Sandro\\workspace\\testeLogin\\screenshot\\2017_3_16_3_59.png"));
byte[] imgData = new byte[imgIs.available()];
imgIs.read(imgData);
String message1 = "";
message1 += "-----------------------------4664151417711" + CrLf;
message1 += "Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"image.png\"" + CrLf;
message1 += "Content-Type: image/jpeg" + CrLf;
message1 += CrLf;
// the image is sent between the messages in the multipart message.
String message2 = "";
message2 += CrLf + "-----------------------------4664151417711--" + CrLf;
lig.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------4664151417711");
// might not need to specify the content-length when sending chunked
// data.
lig.setRequestProperty("Content-Length", String.valueOf((message1
.length() + message2.length() + imgData.length)));
System.out.println("open os");
os = lig.getOutputStream();
System.out.println(message1);
os.write(message1.getBytes());
// SEND THE IMAGE
int index = 0;
int size = 1024;
do {
System.out.println("write:" + index);
if ((index + size) > imgData.length) {
size = imgData.length - index;
}
os.write(imgData, index, size);
index += size;
} while (index < imgData.length);
System.out.println("written:" + index);
System.out.println(message2);
os.write(message2.getBytes());
os.flush();
System.out.println("open is");
is = lig.getInputStream();
char buff = 512;
int len;
byte[] data = new byte[buff];
do {
System.out.println("READ");
len = is.read(data);
if (len > 0) {
System.out.println(new String(data, 0, len));
}
} while (len > 0);
System.out.println("DONE");
}catch(Exception e){
e.printStackTrace();
}finally {
System.out.println("Close connection");
try {
os.close();
} catch (Exception e) {
}
try {
is.close();
} catch (Exception e) {
}
try {
} catch (Exception e) {
}
}
}
}
But I want send all photos in that folder
if you can, show me the code in php too please.

Http call crashes

When i call the http, and during it connection is cutt of..my app crashes.. how can i handle such issue in this code?
This also happens when there is no connection, and the http is called.. also it happens when i returns wrong format ( not json)..
HttpConnection conn = null;
OutputStream os = null;
InputStream is = null;
try {
// construct the URL
String serverURL = "xxxxxxxxxxxxxxxxxxxxxxx"+Common.getConnectionType();
// encode the parameters
URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
byte[] postDataBytes = postData.getBytes();
// construct the connection
conn = (HttpConnection)Connector.open(serverURL, Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent", "BlackBerry/" + DeviceInfo.getDeviceName() + " Software/" + DeviceInfo.getSoftwareVersion() + " Platform/" + DeviceInfo.getPlatformVersion());
conn.setRequestProperty("Content-Language", "en-US");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", new Integer(postDataBytes.length).toString());
// write the parameters
os = conn.openOutputStream();
os.write(postDataBytes);
// write the data and get the response code
int rc = conn.getResponseCode();
if(rc == HttpConnection.HTTP_OK) {
// read the response
ByteVector buffer = new ByteVector();
is = conn.openInputStream();
long len = conn.getLength();
int ch = 0;
// read content-length or until connection is closed
if( len != -1) {
for(int i =0 ; i < len ; i++ ) {
if((ch = is.read()) != -1) {
buffer.addElement((byte)ch);
}
}
} else {
while ((ch = is.read()) != -1) {
len = is.available();
buffer.addElement((byte)ch);
}
}
// set the response
accountsResponse = new String(buffer.getArray(), "UTF-8");
} else {
accountsResponse = null;
}
} catch(Exception e){
accountsResponse = null;
} finally {
try {
os.close();
} catch (Exception e) {
// handled by OS
}
try {
is.close();
} catch (Exception e) {
// handled by OS
}
try {
conn.close();
} catch (Exception e) {
// handled by OS
}
}

number of search result from Bing API

how can i access to number of search result in bing search?
i found this thread:
How to get number of search result from Bing API
in this thread i understand that i should use d->results[0]->WebTotal
but how can i use this line in java?
public static void main(String[] args) throws Exception {
//term1
String searchText = "is";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="WOCKN8uXArczOkQq5phtoEc7usB0kDoPTnbqn0sKWeg";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
//conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
char[] buffer = new char[4096];
while ((output = br.readLine()) != null) {
sb.append(output);
//text.append(link + "\n\n\n");//Will print the google search links
//}
}
conn.disconnect();
int find = sb.indexOf("<d:Description");
int total = find + 1000;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
sb.getChars(find+35, total, buffer, 0);
String str = new String(buffer);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html
I found the answer:
public static void main(String[] args) {
String searchText = "searchtext";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="key_ID";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
//write json to string sb
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
//find webtotal among output
int find= sb.indexOf("\"WebTotal\":\"");
int startindex = find + 12;
int lastindex = sb.indexOf("\",\"WebOffset\"");
System.out.println(sb.substring(startindex,lastindex));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Can't POST data to site using HttpURLConnection on Android

I'm essentially trying to mimic what's been done here through the Android app but for some reason data doesn't get returned as soon as it attempts to post data (it returns fine when I delete the writer.write(finalResult) line).
All I want right now is to be able to search for a user's data once I've sent the username.
Here's my code below:
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", "0");
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
c.setDoOutput(true);
//Attempting to send data!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", paramValue));
OutputStream os = c.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String finalResult = getQuery(params);
Log.d("params", finalResult);
writer.write(finalResult);
writer.close();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
result = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("log_tag", "Error converting result ");
} catch (IOException ex) {
Log.e("log_tag", "Error in http connection ");
}
//json code!
//parse json data
try{
JSONArray jArray = new JSONArray(result);
//for each object in our json array
for(int i =0; i < jArray.length(); i++){
JSONObject json_data =jArray.getJSONObject(i);
String address = "";
//Checks for missing data in address - Need a class for all fields
if (json_data.isNull("address")){
address = "N/A";
}
else
{
address = json_data.getString("address");;
}
//read one line of the response
myListView.setText("Username: "+json_data.getString("username")
+" / " + "Name: " + json_data.getString("name")
+" / " + "E-mail: " + json_data.getString("email")
+" / " + "Address: " + address);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data"+e.toString());
}
}
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();
}
And here is my php script:
<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;
$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT * FROM testusers";
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query."\n";
echo mysql_error();
}
else
{
$rows = array();
while ($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
print json_encode($rows);
}
?>
Since you set the header Content-Length to be 0, the server doesn't even read your content... So anything you send isn't received. You should set Content-Length to finalResult.length().
remove this,
c.setRequestProperty("Content-length", "0");

Categories

Resources