Call POST data from one servlet to another server - java

I am submitting JSON data from my GWT-Client and Passing it to my GWT-Server. And i want to re-submit data to another server and want response from another server to GWT-Client.
I just don't know how can i do this. I tried below code but not working.
My Code is :
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("POST");
StringBuffer jb = new StringBuffer();
URL oracle = new URL("http://www.google.com");
HttpURLConnection connection = null;
connection = (HttpURLConnection) oracle.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setDoInput(true);
request.getInputStream();
OutputStream wr = connection.getOutputStream();
InputStream in = request.getInputStream();
byte[] buffer = new byte[512];
int read = in.read(buffer, 0, buffer.length);
while (read >= 0) {
wr.write(buffer, 0, read);
read = in.read(buffer, 0, buffer.length);
}
wr.flush();
wr.close();
BufferedReader in1 = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in1.readLine()) != null) {
jb.append(inputLine);
}
response.setContentType("text/html");
// Get the printwriter object from response to write the required json
// object to the output stream
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following,
// it will return your json object
out.print(jb.toString());
out.flush();
in1.close();
}
Please help me.

You'll have to send the request to the other server before reading the response
URL oracle = new URL("http://www.anotherserver.com/");
HttpURLConnection connection = null;
connection = (HttpURLConnection) oracle.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream wr = connection.getOutputStream ();
InputStream in = request.getInputStream();
byte[] buffer = new byte[512];
int read = in.read(buffer,0, buffer.length);
while (read >= 0) {
wr.write(buffer,0, read);
read = in.read(buffer,0,buffer.length);
}
wr.flush ();
wr.close ();
BufferedReader in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
jb.append(inputLine);
}
see also Using java.net.URLConnection to fire and handle HTTP requests

In addition, you can use Apache httpclient, it's very simple to implement your requirement, such as :
public static void main(String[] args) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.anotherserver.com/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("key",
"value"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}

Related

How to send an InputStream using POST request

I want to send a mp3 file using POST request from android studio to a flask server. I have read an mp3 file from device and stored in input stream object. The flask server identifies the request to be a POST request and creates the mp3 file. But when I play the mp3 file it does not work. So the connection part does not have any problem. I would like to know how to send this inputstream object in my POST request and get it successfully play the mp3 file on the server (Raspberry Pi).
The part to get the mp3 file and store in inputstream:
if(!DocumentsContract.isDocumentUri(this, data.getData()))
throw new RuntimeException("Not a documentsContract document");
try {
InputStream is = getContentResolver().openInputStream(data.getData());
new Main4Activity.httpAsyncTask417().execute();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
The part of sending the POST request:
public class httpAsyncTask417 extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
try {
String url="http://172.17.57.132/post_songs";
URL obj=new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
String urlParameters = "content=";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.v("HTTPDelete_Check3", "Get returned: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
}catch(java.io.IOException ex) {
}
return null;
}
#Override
protected void onPostExecute(Void v) {
}
}
I solved the problem. Below is the solution.
The part to get the mp3 file and store in inputstream:
//if(!DocumentsContract.isDocumentUri(this, data.getData()))
// throw new RuntimeException("Not a documentsContract document");
try {
is = getContentResolver().openInputStream(data.getData());
uri=data.getData();
file_name=getFileName(uri);
new Main4Activity.httpAsyncTask417().execute();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
The part of sending the POST request:
try {
String url="http://172.17.59.97/post_songs?title="+file_name;
URL obj=new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
/*BufferedReader r = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = r.readLine()) != null) {
wr.writeBytes(line+'\n');
}*/
//wr.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + uri.toString() +"\"" + "\r\n");
byte []buffer = new byte[4096];
int read = 0;
while ( (read = is.read(buffer)) != -1 ) {
wr.write(buffer, 0, read);
}
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.v("HTTPDelete_Check3", "Get returned: " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
}catch(java.io.IOException ex) {
}

Java Bitstamp API market order File not Found

I am trying to make a post from Java to make a market order using my Bitstamp account but the following code is returning a file not found for the URL.
It may be because of CSRF but I am unsure, if anyone has had any experience with the bitstamp API that would be great.
public static void postToken() throws IOException, JSONException {
URL url = null;
String sig = encode();
try {
url = new URL("https://www.bitstamp.net/api/v2/buy/market/" + feedbackType.toLowerCase() +"usd/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);//5 secs
connection.setReadTimeout(5000);//5 secs
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject cred = new JSONObject();
cred.put("key",api_key);
cred.put("signature", sig);
cred.put("nonce", nonce);
cred.put("amount", feedback);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(cred.toString());
out.flush();
out.close();
int res = connection.getResponseCode();
System.out.println(res);
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine() ) != null) {
Log.d(TAG, line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Error: W/System.err: java.io.FileNotFoundException: https://www.bitstamp.net/api/v2/buy/market/btcusd/

Java - How to open one HttpURLConnection for both GET and POST

The request is to GET content from url and handle the content(different every time) properly, then POST the answer back to the same url. I encounter "Can't reset method: already connected" when I try to setRequestMethod("POST") after GET method executed. My code as below
public class MyClass {
/**
* #param args
*/
public MyClass() {};
public void process() {
String url = "http://www.somesite.com/";
String strPage = null;
int n = 0;
try{
URL urlObj = new URL(url);
HttpURLConnection urlConnection =
(HttpURLConnection)urlObj.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String strWhole = null;
while(null != (strPage = reader.readLine())){
strWhole += strPage;
}
//handle content here and calculate result
... ...
//send result below
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String urlParameters = "aa=bb&cc=dd&ee=ff";
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream in1 = urlConnection.getInputStream();
BufferedReader reader1 = new BufferedReader(new InputStreamReader(in));
while(null != (strPage = reader1.readLine())){
System.out.println(strPage);
}
reader1.close();
}
catch(Exception e){
String exception = e.getMessage();
System.out.println(exception);
if (reader != null) {
reader.close();
}
if (reader1 != null) {
reader1.close();
}
}
return;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyClass dp = new MyClass();
dp.process();
}
}
It is impossible to reuse HttpURLConnection instance. But documentation says that under the hood, Java reuses connections for you:
The JDK supports both HTTP/1.1 and HTTP/1.0 persistent connections.
When the application finishes reading the response body or when the application calls close() on the InputStream returned by URLConnection.getInputStream(), the JDK's HTTP protocol handler will try to clean up the connection and if successful, put the connection into a connection cache for reuse by future HTTP requests.
The support for HTTP keep-Alive is done transparently.
Therefore, there is no need to reuse connections manually.
You must set all parameters first. Here's a code i use in my application:
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("app_token", "my token"); // optional header you can set with your own data
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", String.valueOf(urlParameters.getBytes().length));
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
connection.disconnect();
InputStream is = connection.getInputStream();
byte[] b = readWithoutSize(is);
is.close();
The readWithoutSize is:
public static byte[] readWithoutSize(InputStream is) throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
byte[] buf = new byte[512];
int leu;
while ((leu = is.read(buf)) != -1)
baos.write(buf,0,leu);
return baos.toByteArray();
}

inputStream encoding issues (Special characters: ñ, á,...)

Welcome all, I'm currently working on a web-service and I'm having a lot of trouble to make this method work with characters like ñ, ç, á, è,... It's seems to be related with my Input stream, it doesn't seem to be encoding properly, here's the code:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url += urlParameters.toString();
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("charset", "utf-8");
con.setDoOutput(true);
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
//when i check 'con' all seems to be fine
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}
Example:
Inside "con" http:\direction.dom\data\W-S\something?param={example:"castaña"}
and InputStream returns: http:\direction.dom\data\W-S\something?param={example:"casta�a"}
Thanks in advance.
This is a really tricky case because you're dealing with HTTP params. Those can be in any encoding that the user enters in your browser.
Based on your example, your user sends his data in something other than UTF-8. It can be ISO-8859-1, ISO-8859-15 or windows-1252.
You can make push your users towards UTF-8 by setting the right HTTP header to your web form: response.setContentType("text/xml; charset=utf-8):
My partner just figure how to solve it:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("accept-charset", "UTF-8");
con.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(urlParameters.toString());
writer.close();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}

How to send and receive data between Android and GAE-python

I am using this code to send data to the site where my gae-python app is deployed .But I dont know how to receive it on the other end.
protected void tryLogin(String mUsername, String mPassword)
{
HttpURLConnection connection;
OutputStreamWriter requestself = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("http://www.pranshutrial3.appspot.com");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
requestself = new OutputStreamWriter(connection.getOutputStream());
requestself.write(parameters);
requestself.flush();
requestself.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}

Categories

Resources