I want the get some data from my database on my android application. This is my code:
try{
String nome = (String)arg0[0];
String stato = (String)arg0[1];
String link="http://www.example.org/AndroidPage.php";
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
data += "&" + URLEncoder.encode("stato", "UTF-8") + "=" + URLEncoder.encode(stato, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("exception: " + e.toString());
}
If I comment the BufferReader statement I don't get any error. Here is the error..
(The file exist in the server)
http://i.stack.imgur.com/mb3sc.png
UPDATE:
I resolved the problem.. The error was inside the php script, I forgot to write a semicolon.
Did you add the Internet permission to the manifest?
<uses-permission android:name="android.permission.INTERNET" />
Related
I want to scrape posts from Imgur.
Let's say we have this link(permalink): https://imgur.com/gallery/ZXjNfqu/comment/1717354251
I want to load this url via HttpURLConnection and read some data from content(HTML).
I have this code:
try{
//create connection
HttpURLConnection connection = (HttpURLConnection)(new URL(url)).openConnection();
connection.setRequestMethod("GET");
//get response
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//read html
StringBuilder body = new StringBuilder();
try(var reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
String line;
while((line = reader.readLine()) != null){
body.append(line);
}
}
//print html
System.out.println(body.toString());
}else{
//read error content
StringBuilder body = new StringBuilder();
try(var reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))){
String line;
while((line = reader.readLine()) != null){
body.append(line);
}
}
String bodyStr = body.toString().trim();
throw new Exception("Bad HTTP Request: " + responseCode +
" - " + connection.getResponseMessage() +
(bodyStr.isEmpty() ? "" : " - " + bodyStr));
}
}catch(Exception e){ e.printStackTrace(); }
Via HttpURLConnection I get only a part of the real page(what I see in browser). From HTML is missing at least image url and comments.
How I can get all content via HttpURLConnection?
P.S.: Is not necessary to use HttpURLConnection
Edit 1: I think it's because of javascript. But I'm not sure.
I'm trying to use glot.io api to compile java code with curl.
I read a text file :
BufferedReader bufferedReader = new BufferedReader(new FileReader("input.txt"));
StringBuffer stringBuffer = new StringBuffer();
String line = bufferedReader.readLine();
while(line != null){
stringBuffer.append(line);
line = bufferedReader.readLine();
}
If I use no quotation marks, I have no problem when I request the url
URL obj = new URL(url);
HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty ("Authorization", "Token myToken");
conn.setRequestProperty("Content-Type", "application/json");
String data = "{\"files\": [{\"name\": \"main.java\", \"content\": \"" + stringBuffer.toString() + "\"}]}";
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
out.write(data);
out.close();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
System.out.println(bf.readLine());
But when I use String in my code, the web page return 400 error.
Can you help me ?
I am really stuck on this problem and hoping for some help. I automatically log in to a Server and download a Excel (xlsx) File. The download seems to work fine, cause the size is the same as on the server and if I open the file with an XML-Editor it looks valid (compared to other excel Files).
But if I try to open the downloaded file with excel I got a "The file might be corrupt" message and it's not readable.
I tried to change the encoding of the file, the headers of the GET-Request, even tried to write it as Bytestream. Nothing changed.
Here are some relevant code snippets:
public HttpsURLConnection login()
{
HttpsURLConnection connection = null;
String user = "user";
String password = "password";
String authString = user + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
try {
connection = (HttpsURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
connection.setRequestProperty("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//connection.setRequestProperty("Content-Type", "application/vnd.openxml");
connection.setRequestProperty("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//connection.setRequestProperty("Accept", "application/vnd.openxml");
connection.setRequestProperty("User-Agent", USER_AGENT);
connection.connect();
} catch (IOException e)
{
e.printStackTrace();
}
return connection;
}
The download class
private void sendGet(HttpsURLConnection con) throws Exception {
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
String fileName = "test.xlsx";
file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//use FileWriter to write file
FileWriter fw = new FileWriter(file.getAbsoluteFile());
//BufferedWriter bw = new BufferedWriter(fw);
/**CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
encoder.onMalformedInput(CodingErrorAction.REPORT);
encoder.onUnmappableCharacter(CodingErrorAction.REPORT);**/
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(fileName), "UTF-8"
));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
bw.write(inputLine);
}
in.close();
bw.close();
//print result
//System.out.println(response.toString());
}
You can see my attempts in some of the commented lines.
I appreciate any help. Thanks in advance.
I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...
I'm trying to create a Foursquare application using its Java API v2 but I couldn't find any sample source code for the checkin process. I don't need to full source code (authentication, venue search, etc), I just need to checkin part.
Can somebody help me?
import java.net.*;
import java.io.*;
class HelloCheckin {
public static void main(String[] args) {
try {
// Construct data
String data = URLEncoder.encode("ll", "UTF-8") + "=" + URLEncoder.encode("53.576317,0.113386", "UTF-8");
data += "&" + URLEncoder.encode("venueId", "UTF-8") + "=" + URLEncoder.encode("4e144a2cc65bedaeefbb824a", "UTF-8");
data += "&" + URLEncoder.encode("oauth_token", "UTF-8") + "=" + URLEncoder.encode("YOUR_OAUTHTOKEN", "UTF-8");
// Send data
URL url = new URL("https://api.foursquare.com/v2/checkins/add");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
} }
The body of this code came from Simple Java Post