I'm trying to send a http post request as part of a concurrent thread to an application launch.
The code below shows the current code I have now. I tried using the code from Baeldung and similar tutorial sites but I can't seem to get this working.
public static void main(String[] args) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL("http://localhost:5000/").openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setDoOutput(true);
String jsonInputString = "{\"status\": \"UP\"}";
OutputStream os = con.getOutputStream();
//random code here not involved with this quesiton
new Thread(new Runnable() {
public void run() {
while (true) {
try {
os.write(jsonInputString.getBytes());
os.flush();
}
catch (Exception exception) {
System.out.println("Its not working");
}
}
}
}).start();
launch(args);
When I go to type in localhost:5000 in a browser it says it can't connect.
First step make sure local host is working on port 5000, go to http://localhost:5000/ in a regular browser, if thats not working you need to make sure your machine is serving a page on port 5000 properly.
If thats working, the HTTP request may be getting blocked because its not connecting to a server with a valid SSL certificate, you can try changing the webpage to http://www.google.com and see if it gets a response.
Related
I need help, my app was working fine but after renew of Domain name, I started getting error 301. Is something to be fixed in my below code? Though if I use https://Google.com with same code, response code is 200. Hostgator is also not able to find the issue to fix. Can someone help, pls.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://innovativeapps.me");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
int con_respone_code = httpURLConnection.getResponseCode();
Log.i("Response Code: ", con_respone_code + "");
Log.i("Error Message", httpURLConnection.getResponseMessage());
httpURLConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
If i open this using web browser, the url is working fine.
Your site is being redirected to https://innovativeapps.me. When you use the http:// schema, it redirects and returns a 301 letting you know that you need to update your url.
I try to use HttpURLConnection to send a post request to my local (xampp) server with an url like this http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2 , the server php file take param in url and send data to mysql database .
The url works fine on postman agent , and even another get method request works smooth in the android application .
Yet when i try the post method with following code :
public void postOrder() {
TextView tv = findViewById(R.id.tv1);
Thread t = new Thread( new Runnable() {
#Override
public void run() {
HttpURLConnection conn = null;
try {
String link = "http://xxx.xxx.0.3/Company/index.php/booking/c200/p-205/2025-02-09 8:2";
URL url = new URL(link);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(10000 /*ms*/);
conn.setConnectTimeout(15000 /*ms*/);
conn.connect();
}
catch (IOException e) {
Log.d("HTTP error: ", e.toString());
}
finally {
conn.disconnect();
}
}
} );
t.start();
}
It never sent the url and thus no data is stored to database .
And with 6 hours of trial and error , google and searching , i added this line of code :
InputStream is = conn.getInputStream();
And it finally works .
Please answer me why it only works after adding this line of code , what does it do ? I thought the url is triggered right after conn.connect();
Calling connect() only connects, but it doesn't send anything yet. Call getResponseCode() to force the request to be sent. That method is safer than getInputStream() which will throw an exception if the response is not a 2xx (in which case you'd need getErrorStream()).
Does anyone know how I can make a synchronous call via android? I basically do not want to continue any further until I get the response back y/n from the server.
This is the simplest version of the code that I have
URL url = new URL("http://google.com");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
But it gives me this error because it is created on the main thread.
NetworkOnMainThreadException
Any help is greatly appreciated, thanks
Basically you can not do HTTP calls on MainThread.
There are many way arounds like Create a Runnable thread or AsyncTask etc. Try the following code snippet:
new Thread(new Runnable()
{
public void run()
{
try
{
//your HTTP request code..
}
catch (IOException e)
{
//Handle exceptions
e.printStackTrace();
}
}
}).start();
For further reading multithreading see the Android Developer documentation.
I want to develop a java library for bitbucket issues API access.
I've already asked a question about the computation of the HTTP Content-Length header, but this question is specifically about the Bitbucket API and the process of updating an issue (since every other request works well).
The following code doesn't work, giving a 411 Length Required error.
But even more confusing: In the documentation, you are told to use PUT request method. If you "forget" to specify that, status code changes to 200 OK, but leaving the issue unchanged.
public class PutTest {
public static void main(String[] args) throws Exception {
URL u = new URL("https://api.bitbucket.org/1.0/repositories/myname/myproject/issues/1/?title=hello+world");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.addRequestProperty("Authorization", "Basic "+Base64.encodeToString("user:password".getBytes(), false));
c.addRequestProperty("Content-Length", String.valueOf(u.getQuery().getBytes("UTF-8").length));
c.setRequestMethod("PUT");
c.connect();
System.out.println(c.getResponseCode()+" "+c.getResponseMessage());
}
}
My updated code sample works, with help of another question at stackoverflow: How to send PUT, DELETE HTTP request in HttpURLConnection? Looks like not working.
Utilizing connection's OutputStream works.
public class PutTest {
public static void main(String[] args) throws Exception {
URL u = new URL("https://api.bitbucket.org/1.0/repositories/myname/myproject/issues/1/");
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.addRequestProperty("Authorization", "Basic "+Base64.encodeToString(("user:password").getBytes(), false));
c.setRequestMethod("PUT");
c.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(c.getOutputStream());
out.write("title=hello+world");
out.close();
c.connect();
System.out.println(c.getResponseCode()+" "+c.getResponseMessage());
}
}
Greetings,
I am trying to setup a server connection from my BlackBerry Application . I was able to get a response code on the status of the server. Now i have a few values which i have to POST to the server
Its like a registration page values(username, password, age ) have to be sent to the server .
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " + Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
Thats the code i used to get the response code.
I would appreciate it if someone could help me how i can make a POST request to the server..
the server url for status was company.com/app/version/stats
when it for register it would be
company.com/app/register
Thank you
What type of a POST do you use? If you are just passing key-value pairs, then it should be a POST of a "application/x-www-form-urlencoded" content-type.
So, what lacks youe code is:
1). Set a proper content-type on your connection:
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
2). Prepare the content to be sent to the server via the POST:
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("username", username);
encPostData.append("password", password);
encPostData.append("age", age);
byte[] postData = encPostData.toString().getBytes("UTF-8");
3). Set content-length for the connection (this step may be optional - try without this first, probably the BB OS is smart enough to set this automatically):
httpConn.setRequestProperty("Content-Length", String.valueOf(postData.length));
4). Open an OutputStream and write the content to it (the code is simplified):
OutputStream os = httpConn.openOutputStream();
os.write(postData);
os.flush();
...
httpConn = (HttpConnection)connDesc.getConnection();
httpConn.setRequestMethod(HttpConnection.POST);
httpConn.setRequestProperty("username",name);
httpConn.setRequestProperty("password",pass);
....