Must I Get The Response Code From The Server? - java

I have the following code
URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
if(conn.getResponseCode() == 200){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
If I am not interested in the response from the server, can I remove the following code?
if(conn.getResponseCode() == 200){
logger.debug("Success");
} else {
logger.debug("Time out set for 30 seconds");
}
Considering that the code, in it's entirety as it is, causes a java.net.ProtocolException, is there a way to still grab the server response and execute conn.getOutputStream();? In what order? What are the consequences of not obtaining the response aside from the obvious reporting concerns?

The problem is that once you get the response code, you have sent your post. In your code, you don't write anything to the output stream before you get the response. So, you are essentially sending nothing over the post (just that header info), getting the response code, and then trying to write to it again, which is not allowed. What you need to do is write to the output stream first, and then get the response code like so:
public static void main(String[] args) throws IOException {
URL url = new URL(pushURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/restService");
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
String input = writer.getBuffer().toString();
OutputStream os = conn.getOutputStream();
for (char c : input.toCharArray()) {
os.write(c);
}
os.close();
if(conn.getResponseCode() == 200){
System.out.println("Success");
} else {
System.out.println("Time out set for 30 seconds");
}
}
Here's a little tutorial:
Reading and Writing Tutorial

Related

How do I make async http get requests in Java?

I wrote a program where I call many http get request. It takes like half a minute till all the get requests are done but it needs to be done within a second, this can be achieved with calling this method asynchronously, right? But how?
This is what my get request looks like:
public static String dataRequest(String link) throws IOException {
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
String output;
String result = "";
while ((output = br.readLine()) != null) {
result += output;
}
conn.disconnect();
return result;
}
I tried using RxJava but I couldn't get it to work at all. I'm in a Maven JavaFx project. This method is in my getData class.
You can try using thread with ForkJoinPool
For example -> https://www.baeldung.com/java-fork-join

How to make Multiple Post Request using Persistent Connections & Get the response for each request. I am using Java HttpURLConnection Class

I am new to Api.
Aim:- Is to perform Persistent Connections, as opposed to opening a new one for every single request/response pair. Currently I am only getting response for the first request. And for the rest of the response its Empty I don't know is the data for the second request is post or not.
Here is the code for better under standing my Aim and problem.
URL url = null;
HttpURLConnection httpURLConnection=null;
int i=0;
try
{
url = new URL("https:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("http.keepAlive", "true");
httpURLConnection.setRequestProperty("XXXXXX", "XXXXXXXXXXXXXXXXXXXXXXXXXXX");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream = httpURLConnection.getOutputStream();
while (i<10) {
String requestBody = get_data();
outputStream.write(requestBody.getBytes());
outputStream.flush();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String linee;
StringBuffer response = new StringBuffer();
while ((linee = bufferedReader.readLine()) != null) {
response.append(linee);
}
System.out.println("Response:- "+response.toString());
}
else {
// ... do something with unsuccessful response
}
i++;
}
}
catch (IOException ex)
{
System.out.println(ex);
}
This is my Output:-
Response:- {"refId":"0923803","responseList":[{"fileName":"1(1).pdf","dssDocId":"asjckackqwhiq23u29u32"}]}
Response:-
Response:-
Response:-
Response:-
Response:-
Response:-
Response:-
Response:-
Response:-
I hope you understand I don't want to make connection for every single request it's a serious performance issue. First make the connection and then inside the loop keep on write in the API using the same session. The connection should be open for certain period of time or to max number of hit and then again make the connection. Please help I'm stuck.

I post a form to PHP in java, but no response in Ubuntu 18.10

As the title, I want to implement a Web server by Java, the only problem is that I need post a form to login.php and then get the response.
The following code is how I post the data to PHP.
URL url = new URL("http://127.0.0.1:6789" + req.uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Convert string to byte array, as it should be sent
// req.form is the form data to post to the login.php
byte[] postDataBytes = req.form.getBytes(StandardCharsets.UTF_8);
// set the form from request as the post data to PHP
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.getOutputStream().write(postDataBytes);
// get response
int code = conn.getResponseCode();
InputStream is;
if (code == 200) {
is = conn.getInputStream();
fillHeaders(Status._200_);
} else {
is = conn.getErrorStream();
fillHeaders(Status._404_);
}
// get response conetent length from login.php
int length = conn.getContentLength();
The content of login.php is very simple:
<?php
echo 'User name is:' . $_POST['loginName'];
?>
When I debug this part, I will stall in this line
int code = conn.getResponseCode();
That means I cannot get response from login.php
So how can I change the code or the enviornment of ubuntu (maybe the version of php?) to solve this problem.
Thx. XD
If java is the server and PHP is a client you should open listening connection in java.
ServerSocket server = new ServerSocket(8080);
System.out.println("Listening for connection on port 8080 ....");
while (true) {
Socket clientSocket = server.accept();
InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
BufferedReader reader = new BufferedReader(isr);
String line = reader.readLine();
while (!line.isEmpty()) {
System.out.println(line); line = reader.readLine();
}
}

Post BASE64 to server

I am trying to send one image with BASE64 to server and always got 408 with this message "The request body did not contain the specified number of bytes. Got 13.140, expected 88.461". How can I solve that?
I tried to use Retrofit, HttpURLConnection and got the same error. I think that is some parameter on app.
Gson gson = new Gson();
String jsonParam = gson.toJson(enviarPlataforma);
URL url = new URL("");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setFixedLengthStreamingMode(jsonParam.getBytes().length);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam);
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
The UTF-8 bytes must be taken, and send as-is. The DataOutputStream is for something else entirely. As it is one write, you can simply use the OutputStream you get from the connection. A BufferedOutputStream probably serves no purpose.
Flushing before a close is never needed. One needs to flush on a standing, continuing line only.
Try-with-resources closes automatically, also when some exception was thrown.
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
//conn.setDoInput(true);
byte[] content = jsonParam.getBytes("UTF-8"):
conn.setFixedLengthStreamingMode(content.length);
Log.i("JSON", jsonParam.toString());
try (OutputStream os = conn.getOutputStream()) {
os.write(content);
}
I solve my problem. I don't know why but when I'm using Fiddler I got this message.
Thank you guys.

Android Post UTF-8 HttpURLConnection

I am currently developing an application that needs to interact with the server but i'm having a problem with receiving the data via POST. I'm using Django and then what i'm receiving from the simple view is:
<QueryDict: {u'c\r\nlogin': [u'woo']}>
It should be {'login': 'woooow'}.
The view is just:
def getDataByPost(request):
print '\n\n\n'
print request.POST
return HttpResponse('')
and what i did at the src file on sdk:
URL url = new URL("http://192.168.0.148:8000/data_by_post");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
String parametros = "login=woooow";
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("charset","utf-8");
urlConnection.setRequestProperty("Content-Length", "" + Integer.toString(parametros.getBytes().length));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(parametros);
writer.close();
os.close();
I changed the Content-Length to see if that was a problem and then the problem concerning thw value of login was fixed but it was by hard coding (which is not cool).
ps.: everything except the QueryDict is working well.
What could i do to solve this? Am i encoding something wrong at my java code?
thanks!
Just got my problem solved with a few modifications concearning the parameters and also changed some other things.
Having parameters set as:
String parameters = "parameter1=" + URLEncoder.encode("SOMETHING","UTF-8");
then, under an AsyncTask:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
//not using the .setRequestProperty to the length, but this, solves the problem that i've mentioned
conn.setFixedLengthStreamingMode(params.getBytes().length);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(params);
out.close();
String response = "";
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
Then, with this, i got the result from django server:
<QueryDict: {u'parameter1': [u'SOMETHING']}>
which is what i was wanting.

Categories

Resources