Error writing to server using Google API - java

URL url = new URL("https://www.google.com/speech-api/v2/recognize?output=json&lang=en-us&key=mykey");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.write(bytearray);
wr.flush();
wr.close();
InputStream stream = conn.getInputStream(); //throws io exception
so basically I'm trying to send bytearray over httpurlconnection java.io.IOException: Error writing to server at last line.

Related

HTTPURLConnection write command works only with read

I am writing a file into AWS S3 bucket using HTTPURLConnection. This connection's outputstream-write command works only if it is followed by getInputStream or getResponseCode. Please help me to understand this. Is it required to read responseCode?
URL endpointUrl = new URL("muURL");
HttpURLConnection connection = (HttpURLConnection) endpointUrl.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("Authorization", authorization);
connection.setRequestProperty("x-amz-content-sha256", hashPayload);
connection.setRequestProperty("X-Amz-Date", myDate);
connection.setRequestProperty("Content-Type","application/octet-stream");
connection.setRequestProperty("Content-Length",contentLen);
//connection.setRequestProperty("Accept","*/*");
connection.setUseCaches(false);
//connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(payload);
StringBuilder builder = new StringBuilder();
// If I comment this line which gets responseCode , then file is not written in S3.
builder.append(connection.getResponseCode());
wr.flush();
wr.close();
connection.disconnect();
I am expecting this code to work without getResponseCode line.

Android HTTP POST request to server (need explanation)

URL url = new URL("url");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);// i can delete this nothing happens
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(valueIWantToSend);
wr.flush();
wr.close();
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
This code above post my value: valueIWantToSend to my server. Everything is working fine, but i want to ask: Why then i remove this line:
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
Nothing is shown on my server, but then i add this line everything is working great, but why ? I am not using Reader in this connection so what i miss understood?
I think u should call urlConnection.connect()
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.connect();

Java Post Data HttpsUrlConnection or HttpClient 4.5

I am trying to do what I thought was a simple task. I need to POST data to a PHP server. I have tried this solution but in Apache HttpClient 4.5 I can't find BasicNameValuePair in the package. Upon further research I thought I'd try StringEntity...nope not in 4.5 either (that I can find at least). So I tried to do it with HttpsURLConnection. The problem with that is I can't figure out how to add a name to my parameter and with a name, I don't know how to access in PHP with $_POST['name'].
My Current Code:
String json = gson.toJson(data);
URL url = new URL("https://www.domain.com/test.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(json.length()));
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
Try to use DataOutputStream and flush it afterward.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeChars(json);
wr.flush();
wr.close();

How to send post parameter which can be read by php

I have some connection to url:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
How I can send post parameter to this url that php function: http://www.php.net/manual/en/reserved.variables.request.php can read it ? I try to according this question: Java - sending HTTP parameters via POST method easily but with no success. It just display empty array
php code:
print_r($_REQUEST,1)
java code:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("category_name", categoryName);
connection.setRequestProperty("complete", complete);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
connection.getResponseCode();
wr.flush();
wr.close();
connection.disconnect();
You forgot to set the Content-Type header, and you need to write the category_name and complete values as a string to the stream.
Quoting the code from the post you mentioned:
String urlParameters = "param1=a&param2=b&param3=c";
String request = "http://example.com/index.php";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
As you can see, he sets the headers (Content-Type, Charset and Content-Length) and then writes the POST data to the stream.
The POST data is just like the GET format: key-value pairs seperated by &, and the key and value are seperated by =.
As the Content-Type is set to www-form-urlencoded, you need to 'url encode' the key and value values. You can do this using the URLEncoder.encode method.
The urlParameters for your POST data would be:
String urlParameters = "category_name=" + URLEncoder.encode(categoryName) + "&complete=" + URLEncoder.encode(complete);

How to set Content Length REST Request - for Android

I'm trying to connect to a webservice using Java and REST. This is what I've tried, and I get a 411 error.
public static String getSiteToken(String host,String token) throws IOException, JSONException
{
host = host.replace("https://", "http://");
URL url = new URL(host + "/tokens");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", token);
conn.setRequestProperty("Content-Length", "57");
//conn.setFixedLengthStreamingMode(57);
conn.setRequestProperty("Connection","keep-alive");
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader rd = new BufferedReader(isr);
JSONObject json = new JSONObject(rd.readLine());
rd.close();
conn.disconnect();
return json.getString("token");
}
I also tried " setFixedLengthStreamingMode " method, but the application wasn't responding after that line of code. Everything works fine when connecting with REST Client for firefox. I can't figure it out. Thanks!
You aren't writing anything to the body of the request. In that case the content length should be 0 and not 57

Categories