I am making use of the HttURLconnection and URLConnection api's to connect to a PHP file on my web host (x10host). However the connection does not seem to be established and no string data is sent.
I am sure that my PHP code is correct, so am I using the classes incorrectly in the below code?
#Override
protected String doInBackground(String... params) {
StringBuilder respData = new StringBuilder();
InputStream stream = null;
OutputStream os = null;
HttpURLConnection httpUrlConnection;
URLConnection conn;
URL url;
try {
url = new URL("my_url/recieveString.php");
conn = url.openConnection();
httpUrlConnection = (HttpURLConnection) conn;
httpUrlConnection.setUseCaches(false);
//httpUrlConnection.setRequestProperty("User-Agent", "App");
httpUrlConnection.setConnectTimeout(30000);
httpUrlConnection.setReadTimeout(30000);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
os = httpUrlConnection.getOutputStream();
toSubmit = "test";
stream = new ByteArrayInputStream(toSubmit.getBytes(StandardCharsets.UTF_8));
copy(stream, os);
httpUrlConnection.connect();
int responseCode = httpUrlConnection.getResponseCode();
if (200 == responseCode) {
InputStream is = httpUrlConnection.getInputStream();
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is);
char[] buffer = new char[1024];
int len;
while ((len = isr.read(buffer)) != -1) {
respData.append(buffer, 0, len);
}
} finally {
if (isr != null) {
isr.close();
success = true;
}
}
is.close();
} else {
// use below to get error stream
//inputStream = httpUrlConnection.getErrorStream();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
stream.close();
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
return "done";
}
}
Related
I am using the GitHub API to fetch files from a repository. I have the functionality implemented and it does work, I download the needed files but I found something strange, out of the 4 files I get, one is empty (no content inside) even though when I go the to repository and open it there it is clearly with content. The rest of the files have their content in when downloaded. Any idea why that happens?
Here is my code:
public int downloadFromGithub(String repo, String fileName) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", ****);
connection.setRequestProperty("Accept", ****);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK && fileName!=null)
{
return saveFile(connection, fileName);
}
else { return connection.getResponseCode();}
}
public void downloadMultipleFilesFromGithub(String repo,String directoryPath) throws IOException {
URL url = new URL(repo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setRequestProperty("Authorization", *****);
connection.setRequestProperty("Accept", "***");
String response = getResponseBody(connection);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray array = jsonObj.getJSONArray("tree");
for (int i=0; i < array.length(); i++) {
System.out.println(array.getJSONObject(i).get("path"));
String path = array.getJSONObject(i).get("path").toString();
if(path.contains("Scripts")){
String fileName = path.replace(scriptsDirectoryReplace, "");
downloadFromGithub(scriptsRepositoryDirectory+fileName,fileName);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String getResponseBody(HttpURLConnection conn) {
BufferedReader br = null;
StringBuilder body = null;
String line = "";
try {
br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
body = new StringBuilder();
while ((line = br.readLine()) != null)
body.append(line);
return body.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int saveFile(HttpURLConnection connection, String fileName) throws IOException {
// opens input stream from the HTTP connection
String saveFilePath = fileSaveDirectory + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream writer = new FileOutputStream(saveFilePath);
InputStream reader = connection.getInputStream();
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
reader.close();
writer.close();
return connection.getResponseCode();
}
I'm trying to handle this API http://worldtimeapi.org
Here is my code :
#Nullable
public String getResponseFromHttpUrl(#NonNull URL gotUrl) {
Log.v(LOG_TAG, "URI : " + gotUrl);
String timeJSONString = null;
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader = null;
try {
urlConnection = (HttpURLConnection) gotUrl.openConnection();
InputStream inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
if (stringBuilder.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
timeJSONString = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.d(LOG_TAG, "Response : " + timeJSONString);
return timeJSONString;
}
But the problem is my method returns null.
As you can see in below:
V/NetworkUtils: URI : http://worldtimeapi.org/api/timezone/America/Denver
W/System.err: at com.example.timeonearth.NetworkUtils.getResponseFromHttpUrl(NetworkUtils.java:56)
D/NetworkUtils: Response : null
You need to Try getting the input stream from this you can then get the text data as so:-->
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://worldtimeapi.org/api/timezone/America/Denver");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can probably use other Inputstream readers such as buffered reader also.
The problem is that when you open the connection - it does not 'pull' any data.
I need to send some JSONs to another application of mine, for it to store them in a database.
My problem is that the other app keeps getting NULL parameters.
Here is my "sender" app:
public class Main {
public static void main(String[] args) {
ConcurrentLinkedQueue<Employee> employeeQueue = new ConcurrentLinkedQueue<>();
for (int i = 0; i <= 10; i++) {
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
long id = new Random().nextLong() & 0xffffffffL;
employeeQueue.add(new Employee(id, generatedString));
}
try {
while (!employeeQueue.isEmpty()) {
JSONObject json = new JSONObject(employeeQueue.remove());
URL url = new URL("http://localhost:8080/postgressApp/createEmp");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
try {
json.write(osw);
} catch (JSONException e) {
e.printStackTrace();
}
osw.flush();
osw.close();
os.close();
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response from server: " + response.toString());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The "receiver app is a simple spring-boot app waiting for "POST" Requests in a Controller and sending the content of the JSON to a database.
It is working for me.
Use Gson for parsing Java Dto to JSON type. download com.google.code.gson.jar-2.2.4 version.
In your code, I got the issue with parsing.
public class Main {
public static void main(String[] args) {
ConcurrentLinkedQueue<Employee> employeeQueue = new ConcurrentLinkedQueue<>();
for (int i = 0; i <= 10; i++) {
byte[] array = new byte[7]; // length is bounded by 7
new Random().nextBytes(array);
String generatedString = new String(array, Charset.forName("UTF-8"));
long id = new Random().nextLong() & 0xffffffffL;
employeeQueue.add(new Employee(id, generatedString));
}
try {
while (!employeeQueue.isEmpty()) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonEmp = gson.toJson(employeeQueue.remove());
// JSONObject json = new JSONObject(employeeQueue.remove());
URL url = new URL("http://localhost:8080/postgressApp/createEmp");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
try {
osw.write(jsonEmp);
// json.write(osw);
} catch (JSONException e) {
e.printStackTrace();
}
osw.flush();
osw.close();
os.close();
try (BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response from server: " + response.toString());
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Convert JsonObject into byte array then write
byte [] outputBytes=json.toString().getBytes("UTF-8")
OutputStream os = con.getOutputStream();
os.write(outputBytes);
I want to invoke remote server using HttpURLConnection, here is my function:
public String invokeAwvsServer(String api, String param, String method){
System.out.println(api+param);
BufferedReader reader = null;
HttpURLConnection connection = null;
OutputStreamWriter out = null;
try {
URL url = new URL(api);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("X-Auth", apiKey);
connection.connect();
if(method.equalsIgnoreCase("POST")){
out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(param);
out.flush();
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
StringBuffer res = new StringBuffer();
while ((line = reader.readLine()) != null) {
res.append(line);
}
return res.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection != null){
connection.disconnect();
}
if(out != null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "error";
}
I use this function in its own class and works well, but if I call it in other class ,the remote server return 500 status code and JVM throws exception like:
java.io.IOException: Server returned HTTP response code: 500 for URL:...
What`s the reason?Thanks a lot:)
The code pasted below was taken from Javadocs on HttpURLConnection.
I get the following error:
readStream(in)
...as there is no such method.
I see this same thing in the Class Overview for URLConnection at
URLConnection.getInputStream
Where is readStream? The code snippet is provided below:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try
{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in); <-----NO SUCH METHOD
}
finally
{
urlConnection.disconnect();
}
Try with this code:
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
It looks like the documentation is just using readStream() to mean:
Ok, we've shown you how to get the InputStream, now your code goes in readStream()
So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.
Spring has an util class for that:
import org.springframework.util.FileCopyUtils;
InputStream is = connection.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileCopyUtils.copy(is, bos);
String data = new String(bos.toByteArray());
try this code
String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
System.out.println(data);
a complete code for reading from a webservice in two ways
public void buttonclick(View view) {
// the name of your webservice where reactance is your method
new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
//see also:
// https://developer.android.com/reference/java/net/HttpURLConnection.html
//writing to see: https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Log.v("bufferv ", server_response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
//assume there is a field with id editText
EditText editText = (EditText) findViewById(R.id.editText);
editText.setText(server_response);
}
}