Im unable to do HTTP POST using J2ME below is the code that im using which is throwing an exception when I try and write to the OutputStrem.
In the code Below SYSO prints "here5". Please need some guidance. Basically I've put the http connection part in a separate threads run method, to keep it aloof from the UI thread.
public void run(){
HttpConnection http = null;
OutputStream out = null;
String msg = "lat=10&long=20&mac=923873";
try{
String url = "http://xxxx.php";
byte[] data = null;
InputStream istrm = null;
http = (HttpConnection)Connector.open(url);
}
catch(Exception e)
{
System.out.println("here1");
}
try
{
http.setRequestMethod(HttpConnection.POST);
}
catch(Exception e)
{
System.out.println("here2");
}
try{
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("User-Agent", "HttpMidlet/0.2");
http.setRequestProperty("Custom-Property", "MyCustomProperty/1.0; AnotherProperty/debug_0.1");
http.setRequestProperty("Content-Length", ""+msg.getBytes().length);
}
catch(Exception e)
{
System.out.println("here3");
}
try{
out = http.openOutputStream();
}
catch(Exception e)
{
System.out.println("here4");
}
try{
out.write(msg.getBytes());
out.flush();
}
catch(Exception e)
{
System.out.println("here5");
}
}
/**
* Send the data to the URL of Server Site using the POST connection.
*
* #return the response of server.
* #throws Exception
*/
public byte[] send() throws Exception {
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try {
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
if (dout!=null) {
dout.close();
dout = null;
}
int ch;
is = hc.openInputStream();
while ((ch = is.read()) != -1) {
bos.write(ch);
}
res = bos.toByteArray();
} catch (Exception e) {
// if an error occurred connecting to the server.
throw new Exception(e.getMessage());
} finally {
try {
if (bos != null)
bos.close();
if (is != null)
is.close();
if (hc != null)
hc.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return res;
}
According to this Nokia Sample you do not need to call setRequestProperty methods. Another interesting point is the usage of Connector.open(urlstring, Connector.READ_WRITE).
I resolved this by re-installing the emulator.
Related
I'm trying to create an app for android and I'm trying to read my stats from my CloudFlare Dashboard.
The strange thing is that if my code reaches the line ins = con != null ? con.getInputStream() : null; It will say "FileNotFoundException".
The headers are set as they should. Here is the quote from the CF API Documentation:
The dashboard view provides both totals and timeseries data for the given zone and time period across the entire CloudFlare network.
GET /zones/:zone_identifier/analytics/dashboard
- https://api.cloudflare.com/#zone-analytics-dashboard
Some parameters are optional, I double checked my data already and it works fine in Postman.
I tried to use http but CF doesn't allow it.
My code:
class JsonRequest extends AsyncTask<String, String, String> {
private String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while (i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
protected String doInBackground(String... params) {
URL myurl = null;
try {
myurl = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection)myurl.openConnection();
con.setRequestProperty("X-Auth-Email", "email");
con.setRequestProperty("X-Auth-Key", "key");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
con.setDoOutput(false);
} catch (IOException e) {
e.printStackTrace();
}
InputStream ins = null;
try {
ins = con != null ? con.getInputStream() : null; // FileNotFoundException
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return readStream(ins);
}
}
I have a class audio sender which makes a connection to the nodejs server and uploads an audio file in POST method mode.
public class AudioSender implements Callable<JSONObject> {
String outputFile;
AudioSender(String fileLocation){
outputFile=fileLocation;
}
public JSONObject call(){
URL url = null;
HttpURLConnection urlConnection = null;
InputStream audioInputStream=null;
JSONObject response=null;
byte buffer[]=new byte[16];
try {
url = new URL("http://192.168.0.106:3000/upload");
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(16);
urlConnection.setRequestProperty("Content-Type","multipart/form-data");
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setRequestProperty(
"Content-Type", "multipart/form-data;boundary=*****");
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
try {
audioInputStream = new BufferedInputStream(new FileInputStream(outputFile));
Log.d("hello","audioinputstream");
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while(audioInputStream.read(buffer)!=-1) {
out.write(buffer);
Log.d("buffer",buffer.toString());
}
try {
audioInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder total = new StringBuilder();
while(in.read(buffer)!=-1)
total.append(buffer);
Log.d("response",total.toString());
try {
response = new JSONObject(total.toString());
}catch(JSONException e){
Log.e("Response Parse Error", "Could not parse malformed JSON");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response;
}
This is the upload that executes the AudioSender callable.
public void upload() {
JSONObject response=null;
AudioSender sender=new AudioSender(outputFile);
FutureTask<JSONObject> uploadTask=new FutureTask<JSONObject>(sender);
ExecutorService executorService= Executors.newFixedThreadPool(1);
executorService.execute(uploadTask);
Log.d("s","was here");
while(true){
if(uploadTask.isDone()){
try{
response=uploadTask.get();
}catch(InterruptedException|ExecutionException e){
e.printStackTrace();
Log.e("ee","ee",e.getCause());
}
}
}
}
I pretty much know this isn't node js's fault but here's the server code:
app.post('/upload',function(req,res){
console.log("someone called!");
req.on('data',function(chunk){
console.log('res');
console.log(chunk);
});
req.on('end',function(){
console.log("done!");
res.send({'name':'sg'});
});});
When I call upload(), the server console prints
someone called!
done!
I was debugging and found that indeed I am receiving the responded json object from the server. And I don't know if out.write(buffer) is doing the job, but debugging it shows that the buffer value is changing and is in par with my audio file's size.
Please do not suggest using ION or anything else.
I solved the problems by setting up the URLConnection as follows:
boundary = "===" + System.currentTimeMillis() + "===";
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // indicates POST method
urlConnection.setDoInput(true);
urlConnection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"
Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.
URL url;
try {
url = new URL("myurl");
HttpURLConnection 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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have a piece of software which establishes a communication between a PC and a machine, which used to work in Java 1.6, but doesn't anymore in 1.7. The IOException --> "Invalid Http response" is what I get as soon as the getInputStream() method is called. It seems like the method had been improved an is much more sensitive, meaning that responseCode=
-1 result is not specifically checked in Java 1.6.
Assited with Wireshark I checked if both versions (1.6 & 1.7) sent and received same Ethernet frames, and so did both.
I can only resolve this from the PC (client) side...that means no posibility to edit or change the Server code.
I would apreciate any help on how to modify or implement something new to make the code compatible for ver. 1.7 as Im not a former programmer... Thanks
Sequence:
get is called
return readResponse(..) is called
getInputStream() --> IOException
catch (Exception e) {System.out.println("error sending get request " + getURL() + " string: " + requestString); return Error.ethernetException; //TODO
here the console output:
-1
error sending get request ... string: *APPLETCOMMINFO_
strResponse: Ethernet Exception
and the Code:
private String get(String requestString)/* throws ComunicationException*/ {
HttpURLConnection httpURLConnection = null;
OutputStream out = null;
try {
String encodedRequestString = URLEncoder.encode(requestString, "iso-8859-1");
String path = getURL().getPath();
if (!path.endsWith("/")) path = path + "/";
path = path + encodedRequestString;
URL fullURL = new URL(getURL().getProtocol(), getURL().getHost(), getURL().getPort(), path);
httpURLConnection = (HttpURLConnection)fullURL.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
// Set timeout at 5s
httpURLConnection.setConnectTimeout(m_nTimeOut);
httpURLConnection.setReadTimeout(m_nTimeOut);
return readResponse(httpURLConnection);
} catch (Exception e) {
System.out.println("error sending get request " + getURL() + " string: " + requestString);
return Error.ethernetException; //TODO
} finally {
if (out != null) {
try {
out.close();
} catch (Throwable t) {
System.out.println("GET: out.close(), Class: Client");
}
}
if (httpURLConnection != null) {
try {
httpURLConnection.disconnect();
} catch (Throwable t) {
System.out.println("GET: httpURLConnection.disconnect(), Class: Client");
}
}
}
}
/**
* Reads the response from the server into a string.
* The content length header must be set!
* #param connection
* #return
* #throws IOException
*/
private String readResponse(HttpURLConnection connection) throws IOException {
if (connection == null) throw new IllegalStateException("connection must not be null");
connection.connect();
int status = connection.getResponseCode();
System.out.println(status);
// InputStream aaa = connection.getInputStream();
Reader reader = null;
try {
reader = new InputStreamReader(connection.getInputStream(), "iso-8859-1");
int readBufferSize = connection.getContentLength();
if (readBufferSize < 0) {
// use default buffer size
readBufferSize = DEFAULT_READ_BUFFER_SIZE;
}
// if content length was set, read will be done in a single
// iteration because buffer fits...
StringBuffer response = new StringBuffer();
char[] readBuffer = new char[readBufferSize];
int len;
while ((len = reader.read(readBuffer)) > 0) {
response.append(new String(readBuffer, 0, len));
}
return response.toString();
} catch (IOException ioe) {
throw ioe;
} finally {
if (reader != null) {
try {
reader.close();
} catch (Throwable t) {
System.out.println("readResponse: reader.close(), Class: Client");
//log
}
}
}
}
/**
*
* #return the url
*/
public URL getURL() {
return url;
}
}
I just try to post data to google by using the following code,but always got 405 error,can anybody tell me way?
package com.tom.labs;
import java.net.*;
import java.io.*;
public class JavaHttp {
public static void main(String[] args) throws Exception {
File data = new File("D:\\in.txt");
File result = new File("D:\\out.txt");
FileOutputStream out = new FileOutputStream(result);
OutputStreamWriter writer = new OutputStreamWriter(out);
Reader reader = new InputStreamReader(new FileInputStream(data));
postData(reader,new URL("http://google.com"),writer);//Not working
//postData(reader,new URL("http://google.com/search"),writer);//Not working
sendGetRequest("http://google.com/search", "q=Hello");//Works properly
}
public static String sendGetRequest(String endpoint,
String requestParameters) {
String result = null;
if (endpoint.startsWith("http://")) {
// Send a GET request to the servlet
try {
// Send data
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length() > 0) {
urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(result);
return result;
}
/**
* Reads data from the data reader and posts it to a server via POST
* request. data - The data you want to send endpoint - The server's address
* output - writes the server's response to output
*
* #throws Exception
*/
public static void postData(Reader data, URL endpoint, Writer output)
throws Exception {
HttpURLConnection urlc = null;
try {
urlc = (HttpURLConnection) endpoint.openConnection();
try {
urlc.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new Exception(
"Shouldn't happen: HttpURLConnection doesn't support POST??",
e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
OutputStream out = urlc.getOutputStream();
try {
Writer writer = new OutputStreamWriter(out, "UTF-8");
pipe(data, writer);
writer.close();
} catch (IOException e) {
throw new Exception("IOException while posting data", e);
} finally {
if (out != null)
out.close();
}
InputStream in = urlc.getInputStream();
try {
Reader reader = new InputStreamReader(in);
pipe(reader, output);
reader.close();
} catch (IOException e) {
throw new Exception("IOException while reading response", e);
} finally {
if (in != null)
in.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new Exception("Connection error (is server running at "
+ endpoint + " ?): " + e);
} finally {
if (urlc != null)
urlc.disconnect();
}
}
/**
* Pipes everything from the reader to the writer via a buffer
*/
private static void pipe(Reader reader, Writer writer) throws IOException {
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0) {
writer.write(buf, 0, read);
}
writer.flush();
}
}
405 means "method not allowed". For example, if you try to POST to a URL that doesn't allow POST, then the server will return a 405 status.
What are you trying to do by making a POST request to Google? I suspect that Google's home page only allows GET, HEAD, and maybe OPTIONS.
Here's the body of a POST request to Google, containing Google's explanation.
405. That’s an error.
The request method POST is inappropriate for the URL /. That’s all we know.