java SE. How to send post request with binary file? - java

I am working on a java app, to upload images on yfrog.com.
I can post on the API page successfully but without binary files just with a string parameters.
Also the method I use only accept "String".
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.write(data); accept String only.
I tried to put the image path but it doesn't work.

Do yourself a favor and take a look at Apache HttpComponents.

Related

Why Android HttpURLConnection is not able to create Asset on Azure Media Services using REST API?

I am trying to create an Asset on Azure Media Services using REST API from Android. I am following this documentation and this is my code to connect with AMS endpoint from Android,
urlConnection = (HttpURLConnection) this._url.openConnection();
urlConnection.setRequestProperty("Content-Type", String.valueOf("application/json"));
urlConnection.setRequestProperty("DataServiceVersion", String.valueOf("1.0;NetFx"));
urlConnection.setRequestProperty("MaxDataServiceVersion", String.valueOf("3.0;NetFx"));
urlConnection.setRequestProperty("Accept", String.valueOf("application/json"));
urlConnection.setRequestProperty("Accept-Charset", String.valueOf("UTF-8"));
urlConnection.setRequestProperty("Authorization", String.format(Locale.ENGLISH, "Bearer %s", _token));
urlConnection.setRequestProperty("x-ms-version", String.valueOf(2.11));
urlConnection.setRequestProperty("x-ms-client-request-id", UUID.randomUUID().toString());
urlConnection.setRequestProperty("Host", this._host);
urlConnection.setRequestProperty("Content-Length", String.valueOf(this._postData.length));
urlConnection.setRequestProperty("Expect", String.valueOf("100-continue"));
urlConnection.setConnectTimeout(CONNECTION_TIME_OUT);
urlConnection.setReadTimeout(CONNECTION_READ_TIME_OUT);
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
OutputStream wr= urlConnection.getOutputStream();
wr.write(_postData);
wr.flush();
wr.close();
And my _postData variable is byte array which I am converting from json,
_fileName = _fileName.replace(" ", "-");
JSONObject jo = new JSONObject();
jo.put("Name", _fileName+".mp4");
jo.put("Options", String.valueOf(0));
this._postData = jo.toString().getBytes("UTF-8");
I have tried using Google Chrome's REST api client extension to check the post request and It works fine. I got the response I was expecting from chrome's REST api client extension but using Android, I am not getting the same response. I am getting this response from this code which is the step I have already performed before running this code. I have used both endpoints https://media.windows.net/ and https://wamsbayclus001rest-hs.cloudapp.net/ but it is not working from Android. I believe that Android is changing Headers or something is wrong with headers that AMS not parsing properly. Can anyone guide me how to achieve this using Android HttpUrlConnection?
Thanks.
I fixed it by changing OutputStream to DataOutputStream
DataOutputStream wrr = new DataOutputStream(urlConnection.getOutputStream());
wrr.write(this._postData);
wrr.flush();
wrr.close();
and changed my json array to string,
String s = "{\"Name\":\"" + _fileName + ".mp4\", \"Options\":\"0\"}";
and it worked fine.

send http request from IIS to GCM using java

I am trying to send Json message from my [java application server] to [GCM]:
the java server app located on IIS server (Windows server 2008 R2).
here is my function:
public static String post(String apiKey, String json){
try{
URL url = new URL("https://android.googleapis.com/gcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type:", "application/json");
conn.setRequestProperty("Authorization:", "key="+apiKey); // apiKey is valid browser apiKey.
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeUTF(json);
wr.flush();
wr.close();
/*I've deleted the respond check from the question*/
}
but I fail to send!, and does not get any message or exception.
I think that the server itself doesnt let me send http requests!
is this true? how to solve?
I recommend using the Sender and Message objects instead. The sample GCM server code uses those. Sample server code can be seen here.
If you really insist on handling the connection yourself, you can look at the underlying HttpURLConnection implementation of the Sender object here.
It does appear that there are certain differences between the Sender code and your request properties. Hope this helps.

Jsoup HttpConnection. Sending data in non-String type

I'm using jsoup for getting information from different API and parsing it.
Functional compounds enough for all occasions, as long as I did not need to implement something in the likeness of the following code..
URL obj = new URL(url);
javax.net.ssl.HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
String postParams = new StringBuffer("{\"method\": \"getAccountInfo\",
\"params\": [], \"id\": 1}");
conn.setDoOutput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams.toString());
wr.flush();
wr.close();
I spent a lot of searching and re-read all the available documentation, but have not found a method to insert in the post parameters JSONArray as in the example.
Maybe I'm missing something, I will be very grateful for the help, how to implement the code using org.jsoup.HttpConnection.

How to pass input to a web page using a automated script

How to pass input to a php web page using a automated script ,i.e. i just want to know how pass arguments to text fields using a script. like passing input to username and password field of a web page and then pressing submit button(that too with a script).
favorable language: JAVA
Try Selenium. Selenium is great at automating web browsers.
http://seleniumhq.org/
Also has pure support with Java. But not only.
When it comes to custom methods, see ...
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();
source (Java - sending HTTP parameters via POST method easily)
if you web page uses the GET method to accept data (i.e. from URL), just connect to the web pages giving the data you want to pass:
http://www.mysite.com/mypage.html?data0=data0,data1=data1
if the web page uses POST things get a little bit more complicated: you have to forge an appropriate HTML request with all your data in the header (as POST method requires)
You can use the Apache HTTPClient - see the example at:
http://hc.apache.org/httpclient-3.x/methods/post.html
This allows you to simulate submitting a fully filled form directly to the destination page and grab the results.
Remember that, after the call, you have to grab and store the session cookie in the response and resubmit it to the following pages you want to "visit" to stay "logged on"
I would like to show how I would do to pass an input to the HTML. I usually use python to send request to the page where I need to input the data. Before doing that you need to know if you need to supply web-cookies or not, if yes, copy the cookie, if you need to be logged in otherwise not, just check that. Once that is done, you need to know the field names for the input area as you will be using them to POST or GET data using your script. Here is sample usage.
import urllib
import urllib2
import string
headers = {'Cookie': 'You cookies if you need'}
values = {'form_name':'sample text', 'submit':''}
data = urllib.urlencode(values)
req = urllib2.Request('website where you making request to',data,headers)
opener1 = urllib2.build_opener()
page1=opener1.open(req)
#OPTIONAL
htmlfile=page1.read()
fout = open('MYHTMLFILE.html', "wb")
fout.write(htmlfile)
fout.close()

Reading from a URLConnection

I have a php page in my server that accepts a couple of POST requests and process them. Lets say it's a simple page and the output is simply an echoed statement. With the URLConnection I established from a Java program to send the POST request, I tried to get the input using the input stream got through connection.getInputStream(). But All I get is the source of the page(the whole php script) and not the output it produces. We shall avoid socket connections here. Can this be done with Url connection or HttpRequest? How?
class htttp{
public static void main(String a[]) throws IOException{
URL url=new URL("http://localhost/test.php");
URLConnection conn = url.openConnection();
//((HttpURLConnection) conn).setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write("Hello");
wr.flush();
wr.close();
InputStream ins = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
String result = "";
while( (inputLine = in.readLine()) != null )
result += inputLine;
System.out.print(result);
}
}
I get the whole source of the webpage test.php in result. But I want only the output of the php script.
The reason you get the PHP source itself, rather than the output it should be rendering, is that your local HTTP server - receiving your request targeted at http://localhost/test.php - decided to serve back the PHP source, rather than forward the HTTP request to a PHP processor to render the output.
Why this happens? that has to do with your HTTP server's configuration; there might be a few reasons for that. For starters, you should validate your HTTP server's configuration.
Which HTTP server are you using on your machine?
What happens when you browse http://localhost/test.php through your browser?
The problem here is not the Java code - the problem lies with the web server. You need to investigate why your webserver is not executing your PHP script but sending it back raw. You can begin by testing using a simple PHP scipt which returns a fixed result and is accessed using a GET request (from a web browser). Once that is working you can test using the one that responds to POST requests.

Categories

Resources